【问题标题】:setTimeout not working with angular2 typescriptsetTimeout 不适用于 angular2 打字稿
【发布时间】:2017-10-25 10:53:27
【问题描述】:

这是我检查页面是否空闲的 html 代码。如果它空闲了一段时间,我需要抛出不活动警报并注销用户。

<div *ngIf="environmentData" xmlns="http://java.sun.com/jsf/html" (load)="startTimers()" (mousemove)="resetTimers()" (keypress)="resetTimers()">

函数在 typescript 组件中定义如下: timoutNow 变量设置为 10 分钟。但是每次移动鼠标或按下键时,屏幕都会弹出警报。为什么在显示警报之前不等待我设置的时间?

// Start timers.
  startTimers() {
    console.log("inside start timers method");
    console.log("time out number is "+this.timoutNow);
    this.timeoutTimer = setTimeout(this.showTimeout(), this.timoutNow);
    // window.location.href = this.environmentData.logoutUrl;
  }

  showTimeout(){
    console.log("inside show timeout");
    bootbox.alert("You are being timed out due to inactivity!");
  }

  // Reset timers.
  resetTimers() {
    console.log("inside reset timers method");
    clearTimeout(this.timeoutTimer);
    this.startTimers();
  }

【问题讨论】:

    标签: angular typescript settimeout


    【解决方案1】:

    应该是

    this.timeoutTimer = setTimeout(this.showTimeout, <arg2>);  // correct
    

    而不是

    this.timeoutTimer = setTimeout(this.showTimeout(), <arg2>);  // wrong
    

    因为在后者中,您会立即调用回调函数而不是传递引用。

    【讨论】:

    • 非常感谢!那行得通。不敢相信这是个错误。
    • 欢迎:)我添加了解释以供参考。
    • 还有@PoonkodiSivapragasam,您想访问类中的其他功能,您需要使用箭头语法或.bind(this)
    • @cgatian 确实如此,或者,既然没有实例状态,为什么不把它设为function
    • @cgatian 我在 showTimeout 方法中添加了 .bind(this) 以访问类中使用的局部变量。但是,该值仍然未定义。我错过了什么吗?请看下面的代码:bootbox.alert("You are being timed out due to inactivity!", function(){ window.location.assign(this.logoutUrl)}.bind(this));
    猜你喜欢
    • 2017-01-28
    • 2017-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-10
    • 2019-12-28
    • 2017-05-11
    • 1970-01-01
    相关资源
    最近更新 更多