ionic\angular 2: 设置超时后字符串没有更新
ionic\angular 2: string does not updated after settimeout
我正在尝试使用 settimeout(或任何其他回调)更新字符串(class\tag),但没有成功,它与按钮完美配合(当用户单击按钮时更新),但它不适用于 JS settimeout。
你能告诉我我在这里错过了什么吗?
这是我的代码示例:
export class Page1 {
constructor() {
this.greet = "Hi, ";
setTimeout(function(){
this.greet = "Hello, ";
alert("Done");
}, 3000);
}
}
正如您在这个简单代码中看到的那样,我可以在 3 秒后看到警报 "Done",但是问候语没有更新,我应该以某种方式刷新它吗?
感谢您的帮助!
伊兰.
按照您的方式 this
setTimeout 回调中的内容不是 Page1
class 的实例。您需要使用箭头函数来保留上下文:
setTimeout(() => { // <===
this.greet = "Hello, ";
alert("Done");
}, 3000);
查看此link了解更多详情https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Lexical_this
我正在尝试使用 settimeout(或任何其他回调)更新字符串(class\tag),但没有成功,它与按钮完美配合(当用户单击按钮时更新),但它不适用于 JS settimeout。 你能告诉我我在这里错过了什么吗?
这是我的代码示例:
export class Page1 {
constructor() {
this.greet = "Hi, ";
setTimeout(function(){
this.greet = "Hello, ";
alert("Done");
}, 3000);
}
}
正如您在这个简单代码中看到的那样,我可以在 3 秒后看到警报 "Done",但是问候语没有更新,我应该以某种方式刷新它吗?
感谢您的帮助!
伊兰.
按照您的方式 this
setTimeout 回调中的内容不是 Page1
class 的实例。您需要使用箭头函数来保留上下文:
setTimeout(() => { // <===
this.greet = "Hello, ";
alert("Done");
}, 3000);
查看此link了解更多详情https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Lexical_this