我的Angular应用程序中有一个RightSidebarLayout页面,我在其中设置了一个间隔setInterval
并在其上调用了一个函数,用于从工厂函数获取通知。
问题是我想在用户注销后清除它。
这是我的代码RightSidebarLayout.Controller.js
我尝试的第一件事是我使用普通javascript使用了setInterval
方法,但我收到ToastInterval not defined
的错误
var vm = this;
function init(){
var ToastInterval = setInterval(getAllNotifications, 9000); // when user has logged out stop my interval
}
init();
function getAllNotifications() {
// alert(commonApi.IsUserLoggedIn()) // alerts true if logged in else false //working properly
if (!IsUserLoggedIn()){
clearInterval(ToastInterval); // This shows error ToastInterval is undefined as i have defined it in parent environment
return;
}
else {
notificationService.getNoti() // Call a service and get all notification
}
}
我的问题是为什么我没有得到ToastInterval
,,,
lexical environment
2)所以我使用我的ControllerAs
来定义$Interval
回调,它没有给我错误,仍然没有工作,它仍然触发函数
var vm = this;
function init(){
vm.ToastInterval = $interval(getAllNotifications, 9000); // when user has logged out stop my interval
}
init();
function getAllNotifications() {
// alert(commonApi.IsUserLoggedIn()) // alerts true if logged in else false //working properly
if (!IsUserLoggedIn()){
$interval.cancel(vm.ToastInterval);
return;
}
else {
notificationService.getNoti() // Call a service and get all notification
}
}
即使我收到警报我的间隔未被清除,也不会清除间隔。
我做错了什么?
请帮忙,
答案 0 :(得分:-1)
将第一个代码更改为
JS:
var vm = this,
ToastInterval;
function init(){
ToastInterval = setInterval(getAllNotifications, 9000); // when user has logged out stop my interval
}
init();
function getAllNotifications() {
// alert(commonApi.IsUserLoggedIn()) // alerts true if logged in else false //working properly
if (!IsUserLoggedIn()){
clearInterval(ToastInterval); // This shows error ToastInterval is undefined as i have defined it in parent environment
return;
}
else {
notificationService.getNoti() // Call a service and get all notification
}
}
我在init函数之外对变量ToastInterval
进行了十分转换。