我正在尝试学习 promise 的概念并以 Angular 实现。这是我在 stackblit 中的代码。我想要实现的是,每当使用 Angular 中的 Promise 为数组分配任何值时,我都想显示该数组。
我的 HTML 代码是:
<h2>Array values</h2>
<p *ngIf="show">
<span *ngFor="let values of filter">
{{values}}
</span>
</p>
我的 TS 文件是:
filter = [];
show = false;
ngOnInit() {
this.showArray();
}
showArray() {
var a = new Promise(resolve=>{
setTimeout(() => {
this.filter = [3, 4, 4]
resolve('resolved');
}, 0);
});
a.then(function() {
this.show= true;
})
}
每当为我的数组分配任何值(可能来自远程 API)时,我都想将变量 show 设置为 true。我没有得到结果。我已经浏览了许多与 Promise 相关的示例,但找不到这种方式的 Promise 的工作示例。
最佳答案
将您的代码替换为 -
a.then(() => {
this.show= true;
})
您需要使用箭头函数而不是现有函数。
如果您正在使用这段代码 -
a.then(function() {
this.show= true;
})
这不会绑定(bind)到类级别的 show
变量,但模板绑定(bind)是使用类级别变量完成的,这就是现有代码不起作用的原因。
关于javascript - Angular 4 中 Promise 的实现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53319481/