Gary Johnson Gary Johnson - 4 months ago 8
AngularJS Question

Execute function after inner $http call finishes - AngularJS

In my code I am calling this function

loadAllOrders();
. This is the skeleton of its implementation,

$scope.loadAllOrders = function() {
orderSvc.GetAllOrders().then(function(response) {
// Does a bunch of stuff here
});
}


GetAllOrders()
uses a
$http
to get data from a database.
loadAllOrders()
then formats all the data and inserts them into an
ng-repeat
.

I want to be able to call a function when
loadAllOrders()
has finished. For example,

$scope.loadAllOrders().then(
//I am doing something
);


How can this be achieved?

Answer

You can write custom promise for loadAllOrders in angular JS

You have to inject $q service as a dependency on your controllers or service

$scope.loadAllOrders = function() {
var deferred = $q.defer();
    orderSvc.GetAllOrders().then(function(response) {
       // Does a bunch of stuff here
deferred.resolve(response);
    });
 return deferred.promise;
}

https://docs.angularjs.org/api/ng/service/$q

Hope this helps

Comments