使用 $timeout 每 x 次刷新范围 [英] Refresh scope on every x time using $timeout
问题描述
我是 angular 的新手.我想在几分钟后使用 $timeout of angular 来刷新范围.我正在开发一个社交应用程序,几分钟后我需要刷新通知范围.使用服务从 http 请求中获取通知.
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;
});
}
现在我如何在几分钟后发出 http 请求,假设 1 分钟并刷新通知范围.我尝试使用 $timeout 但效果不佳.
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.
推荐答案
但我建议将 $interval
移动到控制器.
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.
传递、解析或拒绝承诺将 $digest
范围.您希望每 x 毫秒获取一次通知并将它们传递到作用域中.
Passing, resolving or rejecting promises will $digest
the scope.
You want to get the notifications every x milliseconds and pass them into the scope.
这篇关于使用 $timeout 每 x 次刷新范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!