【问题标题】:Angular 2 - Using 'this' inside setTimeout [duplicate]Angular 2 - 在 setTimeout 中使用“this”[重复]
【发布时间】:2017-04-27 15:07:25
【问题描述】:

我的课堂上有这样的功能

  showMessageSuccess(){

    var that = this;
    this.messageSuccess = true;

    setTimeout(function(){
      that.messageSuccess = false;
    },3000);

  }

我怎样才能重写这个,这样我就不必在 'that' 变量中存储对 'this' 的引用?如果我在 setTimeout 中使用“this”,则 messageSuccess bool 似乎不会更改/更新。

【问题讨论】:

  • 我相信这不是重复的,角度中的this 子句与普通的javascript不同。 (在最终代码中转换为 _this)

标签: javascript angular scope


【解决方案1】:

您需要使用箭头函数()=>ES6 功能在setTimeout 中保留this 上下文。

// var that = this;                        // no need of this line
this.messageSuccess = true;

setTimeout(()=>{                           // <<<---using ()=> syntax
    this.messageSuccess = false;
}, 3000);

【讨论】:

  • 它总是有效的。可能还有其他问题。我想让你调查一下,或者你可以问一个相关的问题@RomainBruckert
  • 这是一个很好的答案!谢谢,解决了一个大问题。顺便问一下,您能否建议我们在 Angular 7 中还需要在哪里使用 ()=>?
  • @sid:这是 ES6/ES7 标准。如果你使用 typescript,它会在任何地方使用。
  • 好的,所以每次我使用 angular7/typescript 时,我都必须使用 () => 对吗?
  • 在 angular/typescript 中不起作用......仍然必须将外部范围存储在变量中......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-20
  • 2011-12-14
  • 2019-04-06
  • 2018-04-22
  • 2014-08-15
  • 1970-01-01
相关资源
最近更新 更多