我在AngularJS的谷歌论坛上问过这个问题,直到现在还没有听说过。有人能帮我了解一下这里发生了什么吗?
我正在尝试定期刷新资源,但它似乎不起作用。我一直在跟踪它,直到promise是从$http服务获得的,但当在setTimeout中调用该方法时,XHR请求从未创建和激发。然而,如果我在没有setTimeout的情况下也这样做,那么一切似乎都很好。
工作JSFiddle:http://jsfiddle.net/hponnu/Z62QN/2/
window.root_module = angular.module("MyApp", ['ngResource']);
function MainController($scope, $resource) {
$scope.buttonClick = function () {
var res = $resource("http://www.google.com");
res.get({}, function (response) {
alert("response");
}, function (err) {
alert("error");
});
}
}
破碎的JSFiddle:http://jsfiddle.net/hponnu/H8aEt/10/
window.root_module = angular.module("MyApp", ['ngResource']);
window.count = 0;
function MainController($scope, $resource) {
$scope.buttonClick = function () {
setTimeout(function () {
alert("timeout: " + window.count);
var res = $resource("http://www.google.com");
res.get({},
function (response) {
alert("response: " + window.count);
window.count++;
}, function (err) {
alert("error: " + window.count);
window.count++;
});
}, 1000);
}
}
正如您将在损坏的jsfiddle中清楚地看到的,除非再次点击按钮触发点击事件,否则不会为第一个请求触发错误警报。我从AngularJS 1.1.4 开始注意到这一点
有什么想法/建议吗?
PS:https://groups.google.com/forum/#!topic/angular/t28azamT0E是Google群组线程的链接。
您应该始终使用Angularjs的$timeout,而不是setTimeout()
。
function MainController($scope, $resource, $timeout) {
$scope.buttonClick = function () {
$timeout(function () {
...
}, 1000);
}
}