简体   繁体   中英

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?

myService.addJobRating应该返回deferred.promise

您应该从addJobRating返回promise- deferred.promise ,而不是deferred

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM