【发布时间】:2016-01-22 15:50:31
【问题描述】:
我正在尝试在 angularjs 应用程序中使用长轮询。我在控制器中进行了长轮询,该控制器正在更新视图中引用的范围变量。 当我单步执行代码时,正在发生轮询并返回预期的数据,但视图从未更新。
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>
任何关于视图不会更新的想法将不胜感激。
提前致谢。
【问题讨论】:
-
你需要
$scope.$apply()在ajax函数中更新$scope.myTime -
您没有使用 Angular 的
$http进行 ajax 请求,我还看到使用了setTimeout(而不是$timeout/$interval) - 摘要循环不“知道” " 关于这些更改,因此视图不会改变 -
您正在做 Angular 范围之外的两件事。第一个是 jquery 的 AJAX,第二个是 setTimeout。不需要使用其中任何一个,使用角度
$http和$timeout。问题是这些发生在角度范围之外,所以它不知道它需要更新绑定。您是否有机会将 Angular 应用于基于 jquery 的应用程序。 -
感谢大家的建议和反馈。我最初在那里有一条线,我对 angular 还很陌生,但我认为现在这很明显。我将使用现有的角度服务并报告。我正在从一个基于 jQuery 的应用程序中获取一些现有代码,并尝试在这个 Angular 应用程序中重用它。
标签: javascript angularjs long-polling