在Angular中,*ngFor="let item from list | async"是什么意思?

In Angular, what does *ngFor="let item from list | async" mean?

此代码示例中使用了此 https://stackblitz.com/angular/jdamnnmgrae?file=app%2Fautocomplete-overview-example.ts

有问题的代码片段是:

<mat-option *ngFor="let state of filteredStates | async" [value]="state.name">

我还没有见过这种语法,所以我对它的作用感到困惑。当我删除异步调用时,代码不再有效,所以我需要理解它。

我相信这段代码正在创建一个被发送到异步管道的 Observables 列表,但我还没有看到 Angular 的文档中对此进行了记录。知道的请回复。

import {map} from 'rxjs/operators/map';

export class AutocompleteOverviewExample {
// . . . other stuff omitted
  filteredStates: Observable<any[]>;

  constructor() {
    this.filteredStates = this.stateCtrl.valueChanges
    .pipe(
      startWith(''),
      map(state => state ? this.filterStates(state) : this.states.slice())
   );

因此,for 循环可能会在 Observable 上循环,因为 Async 管道采用 Promise 或 Observable,而这不是 Promise。 :-)

有用的链接:

我没能从 FormControl.valueChanges 中找到如何使用管道,但希望在回答这个问题时,这会变得清楚。

(Q) 有人能给我指点一些 Angular 文档来解释“*ngFor | async”语法的含义吗?或提供解释。

搜索答案显示了这些结果

let state of filteredStates | async 语法可以认为是这样的:

let state of (filteredStates | async)

async 管道应用于 filteredStates 变量而不是整个 for 循环。

我认为在查看了您查看的所有其他资源后应该很明显,但是 async 管道很有用,因为它会为您订阅可观察对象(并另外清理订阅,因此您无需担心取消订阅)。

所以,发生的事情是 Angular 正在订阅您的 filteredStates 可观察对象。每次从您的可观察对象流式传输新列表时,Angular *ngFor 指令将遍历流式传输的该列表。

如果没有异步管道,您只需订阅组件中的 filteredStates observable 并将列表作为 属性 存储在组件上(然后您将循环访问组件filteredStates | async)。 注意:有几种方法可以处理取消订阅,这只是一种方法。

<mat-option *ngFor="let state of filteredStates" [value]="state.name">
class AutocompleteOverviewExample {
    filteredStates: State[] = [];
    subscription: Subscription = null;

    constructor() {
        this.subscription = this.stateCtrl.valueChanges
        .pipe(
            startWith(''),
            map(state => state ? this.filterStates(state) : this.states.slice())
        )
        .subscribe(states => this.filteredStates = states);
    }

    ngOnDestroy() {
        if (this.subscription) {
            this.subscription.unsubscribe();
            this.subscription = null;
        }
    }
}