2016-01-22 61 views
1

我想在angularjs應用程序內使用長輪詢。我有一個控制器中的長輪詢,它正在更新在視圖中引用的範圍變量。 當我逐句通過代碼時,發生了輪詢,並且正在返回期望的數據,但視圖永遠不會更新。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> 

爲什麼認爲不會得到更新將大大意識到任何想法。

在此先感謝。

+0

你需要'$範圍。$適用()'只要你更新'$ scope.myTime'在AJAX功能 –

+0

您沒有使用對於ajax請求,我還看到使用'setTimeout'(而不是'$ timeout' /'$ interval') - 摘要循環不會「知道」這些更改,因此視圖不會得到改變 –

+0

你正在做角度範圍之外的兩件事情。第一個是jQuery的AJAX,第二個是setTimeout。沒有必要使用其中任何一種,使用角度'$ http'和'$ timeout'。問題是這些發生在angulars範圍之外,所以它不知道它需要更新綁定。你是否有機會將角度應用於基於jQuery的應用程序。 – ste2425

回答

0

一些普遍性的建議:

  • 不使用jQuery的HTTP方法。你應該更喜歡$ http角度服務。
  • 不使用超時函數。您應該更喜歡$超時角度服務。
  • 不要在您的控制器內調用http遠程服務。你應該創建一個專門的服務。
+0

謝謝。這與其他建議是一致的,除了我會將投票移動到服務中。再次感謝。 – fortpointuiguy

0

進一步的改進可以使用$間隔服務