【问题标题】:Can't set Interval on function无法在功能上设置时间间隔
【发布时间】:2019-03-10 11:58:23
【问题描述】:

这是我正在调用的函数:

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

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

错误类型错误:无法读取未定义的属性“getServices”

那么,有什么想法吗?

【问题讨论】:

    标签: angular ionic-framework ionic4


    【解决方案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(); 
    }
    

    【讨论】:

      【解决方案2】:

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

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

      }

      希望对你有用!

      【讨论】:

        猜你喜欢
        • 2014-10-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-21
        • 1970-01-01
        • 2013-03-01
        • 2016-01-19
        • 1970-01-01
        相关资源
        最近更新 更多