-1
angular.module('adminApp')
.service('subCategoryFinder', ['$http',function($http){
        var self = this;
        self.getSubCategory = function(){
            var data = {};
             $http.get('/app/admin/category/category.json').then(function (response) {
                 data = response.data;
                 console.log(data);
              });
             return data;
        }
}]);

I'm trying to update the data variable inside getSubCategory function but the data variable updates only inside inner functions scope and fails to update the outer function's data variable resulting in empty object i.e. {} as initialized. Thanks in advance!

1 Answers1

-1

The issue is not uncommon for developers who are new to the concept of promises. The $http service returns a promise that is fulfilled by the .then() method. So what you are trying to do is use the response data before the .then() method is called and the promise fulfilled.

Here's a suggested refactor of your service to a more typical pattern:

angular.module('adminApp')
  .service('subCategoryFinder', ['$http', function($http) {
    this.getSubCategory = function() {
      return $http.get('/app/admin/category/category.json');
    };
  }])
  .controller('myController', ['$scope', 'subCategoryFinder', function($scope, subCategoryFinder) {
      subCategoryFinder.getSubCategory.then(function(response) {
        $scope.subCategories = response.data;
      });
    }
  }])
jbrown
  • 3,025
  • 1
  • 15
  • 22