首页 > 解决方案 > 在 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 示例。

标签: javascriptangularecmascript-6promise

解决方案


将您的代码替换为 -

a.then(() => {
  this.show= true;
})

您需要使用箭头功能而不是现有的。

如果您正在使用这段代码 -

a.then(function() {
  this.show= true;
})

这不会绑定到show类级别的变量,但模板绑定是使用类级别变量完成的,这就是现有代码不起作用的原因。

Working Example


推荐阅读