在Angular中,* ngFor =“让列表中的项目|异步”是什么意思?

拍拍

在此代码示例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循环可能会遍历Observables,因为异步管道采用Promise或Observable,而不是Promise。:-)

有用的链接:

我尚未从FormControl.valueChanges中找到如何使用管道,但希望在回答此问题时这将变得清楚。

(Q)谁能指出我一些解释“ * ngFor | async”语法含义的Angular文档?或提供解释。

搜索答案显示了这些结果

丹尼尔·W·斯特林佩尔

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;
        }
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章