0

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?

3
  • 4
    you need to return something from getProducts, so return $http(...); Commented Jan 20, 2020 at 16:54
  • The controller erroneously injects 'staticService' when the service is named 'getService'. Commented Jan 21, 2020 at 2:22
  • I'm sorry for bad editing Commented Jan 21, 2020 at 9:39

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.