【问题标题】:Refresh scope on every x time using $timeout使用 $timeout 每隔 x 次刷新一次范围
【发布时间】:2014-06-25 20:24:39
【问题描述】:

我是 Angular 的新手。我想在几分钟后使用 $timeout of angular 来刷新范围。我正在开发一个社交应用程序,我需要在几分钟后刷新通知范围。使用服务从 http 请求中获取通知。

JS:

App.factory('MyService' ,function($scope,$timeout){
return{
 notification:return function(callback){
      $timeout(function(){
       $http.get("notification/get").success(callback)
      },100000);


}
}); 

function Controller($scope,MyService){

 MyService.notification(function(result){
  $scope.notification =data;
 });

}

现在我如何在几分钟后发出 http 请求,比如说 1 分钟并刷新通知范围。我尝试使用 $timeout,但效果不佳。

【问题讨论】:

    标签: angularjs timeout angularjs-scope


    【解决方案1】:

    但我建议将$interval 移至控制器。

     App.factory('MyService' ,function($scope,$timeout){
      return{
        notification: function(){
            return $http.get("notification/get").success(function(response){
               return response.data;
            });          
        }
      }); 
    
    function Controller($scope,MyService,$interval){  
    
       /**
       * Loads and populates the notifications
       */
       this.loadNotifications = function (){
          MyService.notification().then(function(data){
            $scope.notification =data;
          });
       });
       //Put in interval, first trigger after 10 seconds 
       var theInterval = $interval(function(){
          this.loadNotifications();
       }.bind(this), 10000);    
    
        $scope.$on('$destroy', function () {
            $interval.cancel(theInterval)
        });
    
       //invoke initialy
       this.loadNotifications();
    }
    

    这似乎是一个更好的架构。

    传递、解决或拒绝承诺将$digest 范围。 您希望每 x 毫秒获取一次通知并将它们传递到作用域中。

    【讨论】:

    • 我们如何才能在页面加载时进行第一次调用,然后在假设 10 秒后进一步调用。 ?
    • 记住必须手动取消间隔:$scope.$on('$destroy', function () { $interval.cancel(theInterval) })
    • 移动到web sockets会更好,而不是pull,你可以push到客户端github.com/wilk/ng-websocket
    • Websockets 会强制你的中间件/后端是有状态的,会改变你的架构并且不能在 IE 8-10(?) 中工作。负载平衡器和代理存在一些问题,但是 WS 很棒。
    【解决方案2】:

    您想在超时完成后对其进行实例化。尝试将您的 $timeout 函数更改为:

    var timer = $timeout( function refresh(){
        $http.get("notification/get").success(callback)
        timer = $timeout(refresh, 100000);
    }, 100000);
    

    【讨论】:

    • 我们如何才能在页面加载时进行第一次调用,然后在假设 10 秒后进一步调用。 ?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-12
    • 2022-07-06
    相关资源
    最近更新 更多