从服务返回时,AngularJS承诺不解雇 [英] AngularJS promises not firing when returned from a service
问题描述
可能重复:结果
<一href=\"http://stackoverflow.com/questions/14246442/angularjs-promise-never-resolved-in-controller\">angularjs - 承诺在控制器未曾解决
我在AngularJS服务包一个缓慢的WebSockets服务器,然后调用到从我的控制器,服务。如果我的回调链上回调到回调,一切都运行得很好,任何UI异步更新。
I'm wrapping a slow WebSockets server in a AngularJS service, and then calling into that service from my controllers. If I chain callbacks onto callbacks onto callbacks, everything works just fine, any the UI updates asynchronously.
当我尝试使用 $ q.defer()
清理回调的那些乱七八糟,看来我的递延不会被调用。我熟悉的来自Python的扭曲推迟的概念,所以我认为从概念上就可以工作了 - 但事实并非如此。
When I try to use $q.defer()
to clean up that mess of callbacks, it seems my deferred never gets called. I'm familiar with the concepts of deferred from Python's Twisted, so I think conceptually everything should work - but it doesn't.
这是我能想出,慢的WebSockets服务器模拟了一个setTimeout函数最短的例子。
This is the shortest example I could come up with, the slow WebSockets server is simulated with a setTimeout function.
<!doctype html>
<html ng-app="beta">
<head>
<title>Beta</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.min.js"></script>
<script>
var beta = angular.module('beta', []);
var BetaCtrl = function ($scope, betaServ) {
$scope.button = function () {
serv_result = betaServ.slow();
console.log(serv_result);
serv_result.then(function (result) {
console.log('callback finished');
});
}
}
beta.service('betaServ', function($q) {
this.slow = function () {
d = $q.defer()
setTimeout(function () {
console.log('before resolve');
d.resolve();
console.log('after resolve');
}, 2000);
return d.promise;
}
});
</script>
</head>
<body>
<div ng-controller="BetaCtrl">
<button ng-click="button()">Run</button>
</div>
</body>
</html>
的可能应该运行如下:
The could should run as following:
- 单击按钮
- $ scope.button()被调用;它调用service.slow()函数
- service.slow()返回一个延迟
- 回调登记在推迟
- 推迟火灾,引发了注册的回调(这部分不会发生)
任何想法?谢谢你。
推荐答案
您需要调用你的回调以$适用,因为这就是所谓的角度之外。由于这是一个服务,你需要在你的服务$ rootScope:
You need to call your callback with $apply since it's called outside of Angular. Since this is a service, you'll need to include $rootScope in your service:
beta.service('betaServ', function($q, $rootScope) {
this.slow = function () {
d = $q.defer()
setTimeout(function () {
console.log('before resolve');
$rootScope.$apply(d.resolve);
console.log('after resolve');
}, 2000);
return d.promise;
}
});
这篇关于从服务返回时,AngularJS承诺不解雇的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!