首页 文章

在Angular中,* ngFor =“let item from list |异步“是什么意思?

提问于
浏览
1

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

有问题的代码段是:

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

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

我相信这段代码正在创建一个Observable列表,这些Observable正被发送到异步管道,但我还没有看到它在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循环可能会循环遍历Observables,因为Async管道采用Promise或Observable,而且它不是Promise . :-)

有用的链接:

__用于FormControl.valueChanges的

我无法在FormControl.valueChanges中找到如何使用管道,但希望在回答这个问题时这将变得清晰 .

*(Q) Can someone point me to some Angular documentation that explains what the "ngFor | async" syntax means? or provide an explaination.

搜索答案显示了这些结果

1 回答

  • 3

    可以将 let state of filteredStates | async 语法视为:

    let state of (filteredStates | async)
    

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

    我认为在看了你看过的所有其他资源之后应该很明显,但 async 管道很有用,因为它会为你订阅observable(另外清理订阅所以你不必担心取消订阅) .

    所以,正在发生的是Angular正在订阅你的 filteredStates observable . 每次从您的observable流式传输新列表时,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;
            }
        }
    }
    

相关问题