angularjsangularjs-service

How to wait for my services function to finish in AngularJS?


I made a service with a function.

app.service('getService', ['$http', function($http){    
    this.getProducts = function(log = true){
         $http({
             url: "/admin/products"
         }).then(function successCallback(response) {
             log == true ? console.log(response) : false;
             return response.data;
         }, function errorCallback(response) {
             log == true ? console.log(response) : false;
         });
    }
}]);

After that, I call it and waiting for function to finish, but this not working.

app.controller('categoryCtrl', ['$scope','staticsService', function ($scope, getService) {
    turnonloader();
    $scope.model = getService.getProducts().then(function(){
        turnoffloader();
        console.log("Finished!");
    });
}]);

Which is the best solution?


Solution

  • The service should return the promise:

    app.service('getService', ['$http', function($http){    
        this.getProducts = function(log = true){
             ̶$̶h̶t̶t̶p̶(̶{̶
             return $http({
                 url: "/admin/products"
             }).then(function successCallback(response) {
                 log == true ? console.log(response) : false;
                 return response.data;
             }, function errorCallback(response) {
                 log == true ? console.log(response) : false;
                 //IMPORTANT
                 throw response;
             });
        }
    }]);
    

    Also it is important that the error handler re-throw the error response. Otherwise the promise will be converted from a rejection to a successful promise that returns undefined.