angularjs - 承诺在控制器未曾解决 [英] angularjs - promise never resolved in controller
问题描述
在我的控制器中我得到其他服务的承诺。我添加了一个'然后'条款给它,但'然后'永远不会被调用。
In my controller I'm getting a promise from another service. I add a 'then' clause to it, but the 'then' is never called.
看到这个plunker: http://plnkr.co/edit/dX0Oz1?p = preVIEW ( JavaScript版本)
See this plunker: http://plnkr.co/edit/dX0Oz1?p=preview (javascript version)
fakeLongRunningPromise创建在2秒后自行解决的承诺。
'fakeLongRunningPromise' creates a promise that resolves itself after 2 seconds.
在控制器本身我发一份备忘到控制台,一旦承诺得到解决。
In the controller itself I send a note to the console once the promise is resolved.
我可以告诉大家的承诺正在得到解决,因为解决的承诺,它输出到控制台。为什么它不输出承诺解决?
I can tell that the promise is being resolved because "Resolving promise" it outputted to the console. Why doesn't it output "promise resolved"?
思想也许承诺会超出范围,因为控制器返回?
Thinking maybe the promise is going 'out of scope' because the controller returns?
推荐答案
在AngularJS承诺解决的结果是异步传播,一个$消化周期内。所以,用注册的回调然后
将只要求进入$消化周期。在的setTimeout
执行的AngularJS世界之外,因此不会触发回调。
The AngularJS the result of promises resolution is propagated asynchronously, inside a $digest cycle. So, the callbacks registered with then
will be only called upon entering the $digest cycle. The setTimeout
executes "outside of the AngularJS world", and as such will not trigger callbacks.
该解决方案是使用范围。$适用
或 $超时
服务。这里是$版本适用于:
The solution is to use Scope.$apply
or the $timeout
service. Here is the version with $apply:
window.setTimeout(function() {
console.log("Resolving promise");
$scope.$apply(function(){
deffered.resolve("worked");
});
}, 2000);
下面是一个固定的普拉克(JavaScript的):<一href=\"http://plnkr.co/edit/g5AnUK6oq2OBz7q2MEh7?p=$p$pview\">http://plnkr.co/edit/g5AnUK6oq2OBz7q2MEh7?p=$p$pview
Here is a fixed plunk (JavaScript): http://plnkr.co/edit/g5AnUK6oq2OBz7q2MEh7?p=preview
这篇关于angularjs - 承诺在控制器未曾解决的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!