ahad ahad - 5 months ago 8
AngularJS Question

call a method from finally section of $http in angular

I want call a mthod from finally, by copying allProduct function to finally my problem will be solved ,but i want call this method

app.controller('productController', function($scope, $http) {

$scope.allProduct = function(){
$http({
method: 'post',
url: 'ajax.php',
data: $.param({'type' : 'allProduct' }),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data){
$scope.products = data;
})
.error(function() {
$scope.data = "error in fetching data";
});
}
$scope.saveProduct = function(){

var productName = $scope.nProductName;
var productCode = $scope.nProductCode;
var productImage = $scope.nProductImage;
var productCategory = $scope.nProductCategory;
var details = tinymce.activeEditor.getContent();

$http({
method: 'post',
url: 'ajax.php',
data: $.param({'type' : 'saveProduct',
'productName':productName,
'productCode':productCode,
'productImage':productImage,
'productCategory': productCategory,
'productDetails':details}),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data){
$scope.products = data;
})
.error(function() {
$scope.data = "error in fetching data";
})
.finally(allProduct);
}});


how to call allProduct method from finally??

Answer

As JB Nizet mentions, success/error are deprecated. You should use then/catch to chain your promises. Check the $http doc: https://docs.angularjs.org/api/ng/service/$http

I would declare your "allProducts" callback as a function then reference it when you need it in your controller, like this:

$scope.allProduct = allProductCallback;

$scope.saveProduct = function(){
    ...
    })
    .then(function(data){            
        $scope.products = data;
    })
    .catch(function() {
        $scope.data = "error in fetching data";
    })
    .finally(allProductCallback);
}});

function allProductCallback(){
    $http({
        method: 'post',
        url: 'ajax.php',
        data: $.param({'type' : 'allProduct' }),
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    })
    .then(function(data){           
        $scope.products = data;
    })
    .catch(function() {
        $scope.data = "error in fetching data";
    });
}