我正在尝试使用 settimeout (或任何其他回调)更新字符串(类\标签),但没有成功,它与按钮完美配合(当用户单击按钮进行更新时),但是它不适用于 JS settimeout。 你能告诉我我在这里缺少什么吗?
这是我的代码示例:
export class Page1 {
constructor() {
this.greet = "Hi, ";
setTimeout(function(){
this.greet = "Hello, ";
alert("Done");
}, 3000);
}
}
正如您在这个简单的代码中看到的,我可以在 3 秒后看到“完成”警报,但问候语没有更新,我应该以某种方式刷新它吗?
感谢您的帮助!
伊兰。
最佳答案
按照您的方式,setTimeout 回调中的 this
不是 Page1
类的实例。您需要使用箭头函数来保留上下文:
setTimeout(() => { // <===
this.greet = "Hello, ";
alert("Done");
}, 3000);
请参阅此链接了解更多详细信息 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Lexical_this
关于javascript - ionic \Angular 2 : string does not updated after settimeout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37650200/