Javascript 迭代承诺<;任何[]>;用*ngFor?

Javascript 迭代承诺<;任何[]>;用*ngFor?,javascript,angular,typescript,promise,Javascript,Angular,Typescript,Promise,获取一个无限循环,尝试遍历此函数调用产生的承诺: public CUSTOMERS = [ {"id":1,"name":"Crypto Joe", "description":"Love Crypto in the Morning"}, {"id":1,"name":"Crypto Sue", "description":"Love Crypto in the Evening"} ]; loadCustomers():Promise<any[]> {

获取一个无限循环,尝试遍历此函数调用产生的承诺:

 public CUSTOMERS = [
    {"id":1,"name":"Crypto Joe", "description":"Love Crypto in the Morning"},
    {"id":1,"name":"Crypto Sue", "description":"Love Crypto in the Evening"}
];

    loadCustomers():Promise<any[]> {
      return of(this.CUSTOMERS).toPromise()
    }

想法?这是stackblitz演示:


我更新了演示,使用了
changeDetection:ChangeDetectionStrategy.OnPush
,但它仍然会导致无限循环。也许这只能通过观察来实现?

问题在于变化检测。 因此,一旦第一个客户添加到DOM中,angular就会检测到更改并调用loadCustomers(),这将导致无限循环


将检测更改为“OnPush”或绑定到属性而不是方法或getter。

这是否回答了您的问题?考虑到您通过
async
管道使用
Promise
,您还可以提供一个可观察的(
返回(this.CUSTOMERS);
)。
async
管道也能很好地处理这个问题。我将原始演示更改为使用“changeDetection:ChangeDetectionStrategy.OnPush”,但它不起作用。你知道为什么吗?酷-绑定这个属性是有效的:我把原来的演示改为使用'changeDetection:ChangeDetectionStrategy.OnPush',但它不起作用。你知道为什么吗?正如Philipp Meissner已经提到的,考虑使用可观察而不是承诺。因此,您只需使用(this.CUSTOMERS),属性的类型将为customer$:Observable。很高兴我能帮助你,如果你想使用变更检测,你必须手动触发变更检测。在构造函数中注入ChangeDetectorRef并调用changeDetection.detectChanges()。这将重新触发渲染
<li *ngFor="let customer of loadCustomers() | async">
    <h3>{{customer.name}}</h3>
    <code> {{customer.description}} </code>
</li>
</ul>