javascript - 在 Angular 4 中实现承诺时出错
问题描述
我正在尝试学习承诺的概念并以角度实现。这是我在stackblit中的代码。我想要实现的是,每当使用角度中的 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;
})
这不会绑定到show
类级别的变量,但模板绑定是使用类级别变量完成的,这就是现有代码不起作用的原因。
推荐阅读
- jquery - 使用 Ajax 和 Jquery 时部分空 POST 或 QueryDict
- postgresql - Postgresql 模式和数据比较
- maven - 如何在构建期间跳过 jacoco 覆盖检查?
- javascript - 关于 IDE 中 node_modules 自动完成的问题
- javascript - 如何使用 Javascript 在点击时删除 HTML div
- vagrant - Vagrant 未能解包 Ubuntu Bionic 盒子
- python-3.x - KeyError - 无法解析 #python
- android - **bind() with** 和 **bind() from** 之间的 Android kodein 区别
- google-app-engine - 如何识别哪些 VM 实例正在使用 v0.1 和 v1beta1 端点作为应用引擎?
- python - 如何找到硬盘的最后一个扇区?