Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 after few minutes. Getting notification from a http request using service.

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

}

Now how can i make http request after few minutes let'say 1 minute and refresh notification scope. I tried using $timeout but things are not working fine.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
996 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...