Angular 2 - 在setTimeout中使用'this' [英] Angular 2 - Using 'this' inside setTimeout

查看:118
本文介绍了Angular 2 - 在setTimeout中使用'this'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的课程中有这样的功能

I have a function like so in my class

  showMessageSuccess(){

    var that = this;
    this.messageSuccess = true;

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

  }

我如何重写这个,所以我不这样做必须在'that'var中存储'this'的引用?如果我在setTimeout中使用'this',则messageSuccess bool似乎不会更改/获取更新。

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.

推荐答案

你需要使用ArrowFunction ()=> 在<$ c $中保留 上下文C>的setTimeout 。

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

这篇关于Angular 2 - 在setTimeout中使用'this'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆