1

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?

1
  • It shouldn't work,...you can't return from an AJAX call, you have to use a callback. Commented Sep 15, 2014 at 14:25

3 Answers 3

12

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;
 });    
Sign up to request clarification or add additional context in comments.

Comments

1

Calls to the $http service are async, which means you need to return a promise (and not a value):

this.prepTime = function() {
    return $http({
      url: '/prep_times/index.json',
      method: 'GET'
    });          
};

And on the controller:

angular.module('recipeapp')
  .controller('recipeCtrl', ['$scope', 'prepTimeService', function($scope, prepTimeService){
    $scope.prep_time = prepTimeService.prepTime()
      .success(function (data, status, header, config){
        $scope.someVar = data;
      });
}]);

Comments

1

Wrap answer with promise:

var self = this;

var deferred = $q.defer();

self.getPrepTimes = function() {
        $http({
            url: '/prep_times/index.json',
            method: 'GET'
        })
                .success(function(data, status, headers, config) {

                    if (data.error === undefined) {
                        deferred.resolve(data);
                    } else {
                        if (data.error !== undefined) {

                        } else {
                            deferred.reject(data);
                        }
                    }

                }).error(function(data, status, headers, config) {
            deferred.reject(data);
        });
        return deferred.promise;
    };

In controller call it:

 prepTimeService.getPrepTimes().then(function(result) {
     $scope.prep_time = result;
    },
    function(error) { 
     // show alert           
   });

2 Comments

thanks for the answer, I'm pretty new to angular and for me promise are still bit confusing.. so trying to keep away from them for the moment :)
@sameera207 for the future homework :) promises give you ability to pass to controller also errors. Consider that http failed and you want to show up some popup, in this case you reject the answer and in controller enter to function(error)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.