我正在尝试在 angularjs 应用程序中使用长轮询。我在 Controller 内进行长轮询,该 Controller 正在更新 View 中引用的范围变量。 当我单步执行代码时,正在发生轮询并返回预期的数据,但 View 从未更新。
longpolltest.js
var myApp = angular.module('myApp', []);
myApp.controller('MyController', function($scope, $timeout) {
$scope.value = 1;
function poll() {
var d = new Date();
var n = d.getTime();
$scope.value++;
$.ajax({
type: 'GET',
url: '/gs/async?millis=' + n,
contentType: "application/json; charset=utf-8",
async: true,
cache: false,
success: function(data) {
var obj = jQuery.parseJSON(data);
if (obj.type == 'ServerTime')
$scope.myTime = object.Data.Time;
setTimeout("poll()", 1000);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("error: " + textStatus + " " + errorThrown);
setTimeout("poll()", 10000);
}
});
}
poll();
});
longpolltest.html
<!DOCTYPE html>
<html>
<head lang="en">
<!-- jQuery JavaScript -->
<script src="js/ext/jquery-1.12.0.min.js"></script>
<!-- angular library -->
<script src="js/ext/angular/angular.min.js"></script>
<script src="js/ext/angular/angular-route.min.js"></script>
<script src="js/longpolltest.js"></script>
<meta charset="UTF-8">
<title>Long poll test</title>
</head>
<body ng-app="myApp">
<div>
<div ng-controller="MyController">
<p>
Time: {{myTime}}
Poll#: {{value}}
</p>
</div>
</div>
</body>
如果有任何关于 View 无法更新的想法,我们将不胜感激。
提前致谢。
最佳答案
一些一般性建议:
- 不要使用 jquery http 方法。您应该更喜欢 $http Angular 服务。
- 不要使用超时功能。您应该更喜欢 $timeout Angular 服务。
- 不要在 Controller 内调用 http 远程服务。您应该创建专门的服务。
关于javascript - AngularJS 长轮询 View 未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34950644/