javascript - AngularJS 长轮询 View 未更新

标签 javascript angularjs long-polling

我正在尝试在 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 服务。
  • 不要使用超时功能。您应该更喜欢 $t​​imeout Angular 服务。
  • 不要在 Controller 内调用 http 远程服务。您应该创建专门的服务。

关于javascript - AngularJS 长轮询 View 未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34950644/

相关文章:

javascript - 如何从 javascript 选择 div 中的文本(用于复制到剪贴板)?

javascript - 未定义的属性 : stdClass: in using AngularJS + PHP

php - 长轮询 - 消息系统

javascript - 在 dom 中有大量输入标签的 IE 上,聚焦和/或选择输入元素速度较慢

javascript - 如何使用 jQuery 禁用文本选择?

javascript - 如何访问 AngularJS 中组合框的选定元素?

javascript - Google Analytics Real Time 如何运作?

javascript - 长轮询避免发送 OPTIONS 和 GET 组合[跨域]

javascript - 激活可滚动的 div

javascript - 向 Controller 添加服务时出现未知提供商