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

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

问题描述

我的班级有这样的功能

  showMessageSuccess(){

    var that = this;
    this.messageSuccess = true;

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

  }

我怎样才能重写它,这样我就不必在that"变量中存储对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.

推荐答案

你需要使用箭头函数()=> ES6特性来保留<代码>this setTimeout 中的上下文.

You need to use Arrow function ()=> ES6 feature 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天全站免登陆