Angular 2 - Using 'this' inside setTimeout

2019-01-31 04:50发布

This question already has an answer here:

I have a function like so in my class

  showMessageSuccess(){

    var that = this;
    this.messageSuccess = true;

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

  }

How can I re-write this so I don't have to store a reference to 'this' in the 'that' var? If I use 'this' inside the setTimeout, the messageSuccess bool doesn't seem to change/get updated.

1条回答
smile是对你的礼貌
2楼-- · 2019-01-31 05:50

You need to use ArrowFunction ()=> to preserve this context within setTimeout.

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

setTimeout(()=>{    //<<<---    using ()=> syntax
      this.messageSuccess = false;
 }, 3000);
查看更多
登录 后发表回答