很惊讶地看到为什么
angularjs promise没有使用$interval服务多次解决.以下是我的代码.变量i多次递增,但承诺仅解析一次.
var app = angular.module('plunker',[]); app.controller('MainCtrl',function($scope,myService) { myService.then(function(result) { $scope.i = result; }); }); app.factory('myService',function($interval,$q) { var deferred = $q.defer(); var i = 0; $interval(function() { i += 1; deferred.resolve(i); },2000); return deferred.promise; });
使用AngularJS,您可以使用$q(
https://docs.angularjs.org/api/ng/service/ $q)的通知功能而不是解析:
原文链接:https://www.f2er.com/angularjs/140423.htmlvar app = angular.module('plunker',myService) { // Notice that the third callback is for notify myService.then(null,null,function(result) { $scope.i = result; }); }); app.factory('myService',$q) { var deferred = $q.defer(); var i = 0; $interval(function() { i += 1; deferred.notify(i); },2000); return deferred.promise; });
您可能希望添加$interval.cancel()以在某个点/条件(https://docs.angularjs.org/api/ng/service/ $interval)停止循环.