[英]AngularJS : Injecting a promise into a controller using “resolve”
[英]Can't Resolve My Promise in Controller - AngularJS
我有一个服务函数,看起来像:
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;
};
我可以像这样在控制器中调用以上内容
console.log(myService.addJobRating(646, 9999, 'good-result')
这会将预期的Promise对象记录在控制台日志中。 但是,如果我尝试使用以下方法来解决承诺:
myService.addJobRating(646, 9999, 'good-result').then(function(data){
console.log(data);
}, function(data){
console.log(data);
});
我收到一个TypeError: undefined is not a function
错误。
为什么会这样呢?
myService.addJobRating
应该返回deferred.promise
。
您应该从addJobRating返回promise- deferred.promise
,而不是deferred
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.