【问题标题】:In Angular, what does *ngFor="let item from list | async" mean?在 Angular 中,*ngFor="let item from list | async" 是什么意思?
【发布时间】:2018-09-07 20:40:28
【问题描述】:

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

有问题的代码sn-p是:

<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 上循环,因为 Async 管道采用 Promise 或 Observable,而它不是 Promise。 :-)

有用的链接:

我无法从 FormControl.valueChanges 中找到管道是如何使用的,但希望当这个问题得到解答时,这一点会变得清晰。

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

搜索答案显示了这些结果

【问题讨论】:

  • 看不到难以理解的东西。您已经清楚地找到了AsyncPipe 文档,那么您还需要什么?
  • 这意味着filteredStates是一个promise或observable,它不会在组件初始化时初始化/定义,并且会在某个未知时间异步解决。并且当它执行时,for循环将运行并显示模板,这与其他可迭代对象(如数组)不同,如果数组未定义或不可用,则会在组件初始化期间抛出错误

标签: angular typescript ngfor


【解决方案1】:

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

【讨论】:

  • 感谢您展示了做同样事情的另一种方式。您的代码示例帮助我了解异步在做什么。而现在,很明显。 :-) 再次感谢!
猜你喜欢
  • 2011-11-23
  • 2020-06-26
  • 2017-10-21
  • 2022-10-21
  • 1970-01-01
  • 2020-12-18
  • 1970-01-01
  • 2017-08-25
  • 1970-01-01
相关资源
最近更新 更多