Refresh scope on every x time using $timeout

前端 未结 2 788
天涯浪人
天涯浪人 2020-12-16 02:37

I am a newbie to angular. I want to use $timeout of angular to refresh scope after few minutes. I am working on an social app where i need to refresh notification scope afte

相关标签:
2条回答
  • 2020-12-16 02:58

    You want to instantiate the timeout after it finishes. Try changing your $timeout function to something like:

    var timer = $timeout( function refresh(){
        $http.get("notification/get").success(callback)
        timer = $timeout(refresh, 100000);
    }, 100000);
    
    0 讨论(0)
  • 2020-12-16 03:04

    But i would suggest to move the $interval to the controller.

     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();
    }
    

    This seems like a better architecture there.

    Passing, resolving or rejecting promises will $digest the scope. You want to get the notifications every x milliseconds and pass them into the scope.

    0 讨论(0)
提交回复
热议问题