Lloyd Banks
Lloyd Banks

Reputation: 36648

Can't Resolve My Promise in Controller - AngularJS

I have a service function that looks like:

this.addJobRating = function(jobId, userId, rating){
    var deferred = $q.defer();
    $http.post('/to/my/api', {job_id: jobId, user_id: userId, rating: rating})
        .success(function(data){
            deferred.resolve(data)
        })
        .error(function(data){
            deferred.reject('promise call failed');
        });
    return deferred;
};

I can call the above in my controller like so

console.log(myService.addJobRating(646, 9999, 'good-result')

This logs the expected promise object in console log. But if I try to resolve the promise using:

myService.addJobRating(646, 9999, 'good-result').then(function(data){
    console.log(data);
}, function(data){
    console.log(data);
});

I get an TypeError: undefined is not a function error.

Why is this happening?

Upvotes: 0

Views: 121

Answers (2)

Mike Daly
Mike Daly

Reputation: 148

You should be returning the promise - deferred.promise - from addJobRating, not deferred.

Upvotes: 3

jdp
jdp

Reputation: 3516

myService.addJobRating should return deferred.promise.

Upvotes: 4

Related Questions