kme*_*lvn 8 future deferred angularjs
我在AngularJS服务中包装一个慢的WebSockets服务器,然后从我的控制器调用该服务.如果我将回调链接到回调到回调,一切正常,任何UI异步更新.
当我尝试用来$q.defer()清理那些混乱的回调时,似乎我的延迟永远不会被调用.我熟悉Python扭曲的延迟概念,所以我认为概念上一切都应该有效 - 但事实并非如此.
这是我能想到的最短的例子,使用setTimeout函数模拟慢速WebSockets服务器.
<!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>
Run Code Online (Sandbox Code Playgroud)
可以运行如下:
有任何想法吗?谢谢.
Man*_*y D 29
您需要使用$ apply调用回调,因为它在Angular之外调用.由于这是一项服务,您需要在服务中包含$ rootScope:
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;
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7659 次 |
| 最近记录: |