无法设置间隔功能

时间:2019-03-09 22:43:30

标签: angular ionic-framework ionic4

这是我正在调用的函数:

refreshServices() {
this.services = this.monitorService.getServices(); }

我这样调用构造函数:

constructor(private localNotifications: LocalNotifications,
public monitorService: MonitorService) {
this.refreshServices(); }

这很好,但是当我这样做时:

constructor(private localNotifications: LocalNotifications,
public monitorService: MonitorService) {
setInterval(this.refreshServices,100000); }

不起作用...这是控制台中的错误消息:

  

错误TypeError:无法读取未定义的属性'getServices'

那么,有什么事吗?

2 个答案:

答案 0 :(得分:1)

问题是setInterval在另一个上下文中调用传递的函数,其中函数内部的this指向全局对象(window),而不是setInterval所来自的类叫做。这意味着执行此行

this.monitorService.getServices();

等于以下内容

window.monitorService.getServices();

由于window没有初始化monitorService属性,因此出现该错误。要解决此问题,您需要将函数的上下文绑定到当前类

//this code ensures that "this" inside "refreshServices" will refer to the class instance
setInterval(this.refreshServices.bind(this),100000);

另一种可能的解决方案是使用箭头功能,该功能使用封闭范围的上下文

refreshServices = () => {
    this.services = this.monitorService.getServices(); 
}

答案 1 :(得分:0)

您必须使用箭头功能来解决您的问题。 似乎您需要以下代码:

refressToken() {
this.checkRefreshTokenThread = setInterval(() => {
  const expiredTime = this.authStore.getExpiredTimeLocalStorage();
  const nowTime = String(new Date().getTime());
  const nowTimeJava = Number(nowTime.substr(0, 10));
  this.timeOfRefresh = (expiredTime - nowTimeJava) < CONSTANT._9MINUTES;
  this.isExpired = expiredTime < nowTimeJava;
  if (this.isExpired) {
    this.authenticationService.logout();
    this.router.navigate(['/login']);
  }else if (this.timeOfRefresh && !this.authStore.getIsReadyLocalStorage()) {
     this.authStore.setIsReadyLocalStorage('true');
  }
}, CONSTANT._1MINUTE);

}

从服务获取数据后,应清除以下时间间隔:

  clearIntervalRefreshToken() {
clearInterval(this.checkRefreshTokenThread);

}

希望对您有用!