Search code examples
angularjsangular-services

AngularJS : service not returning value


I'm trying to write an Angular service and it seems like there is something missing. My problem is its not returning any value to my Angular controller

getPrepTimes() method is not returning the http data

But when I check the network (via Chrome dev tools) it will correctly call the external api and return a json object as a response

#my service
'use strict';
angular.module('recipeapp')
  .service('prepTimeService',['$http', function($http){
      this.prepTime = getPrepTimes();

      function getPrepTimes(){
          $http({
            url: '/prep_times/index.json',
            method: 'GET'
          })
          .success(function (data, status, header, config){
            return data;
          });
      };
  }
  ]);




#controller
'use strict';

angular.module('recipeapp')
  .controller('recipeCtrl', ['$scope', 'prepTimeService', function($scope, prepTimeService){
     $scope.prep_time = prepTimeService.prepTime;
  }]);

When I checked the method getPrepTimes() with returning a string it works. What could be missing here?


Solution

  • A couple things are wrong with the above. You assign this.prepTime to getPrepTimes(). The () there will invoke getPrepTimes immediately, and not when you actually call it! You also need to utilize callbacks to get your data back and use it:

    angular.module('recipeapp').service('prepTimeService',['$http', function($http){
        this.prepTime = getPrepTimes;
    
        function getPrepTimes(callback) {
            $http({
                url: '/prep_times/index.json',
                method: 'GET'
            }).success(function (data, status, header, config){
                callback(data);
            });
        };
    }]);
    

    And now use it like so:

     prepTimeService.prepTime(function(data) {
         $scope.prep_time = data;
     });