【发布时间】: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。 :-)
有用的链接:
https://angular.io/guide/rx-library - 用于地图、过滤器
https://angular.io/api/forms/FormControl for FormControl.valueChanges
我无法从 FormControl.valueChanges 中找到管道是如何使用的,但希望当这个问题得到解答时,这一点会变得清晰。
(Q) 谁能给我一些 Angular 文档来解释“*ngFor | async”语法的含义?或提供解释。
搜索答案显示了这些结果
Using an array from Observable Object with ngFor and Async Pipe Angular 2 - 我认为我的问题很相似,但我阅读了那个答案,但没有解释,只有一个代码示例。
Use async pipe in ngFor on Observable of Observables (Angular) - 更多语法我不明白。
https://blog.thoughtram.io/angular/2017/02/27/three-things-you-didnt-know-about-the-async-pipe.html - 这看起来像是我的问题的答案。但既然我花了这么多时间来写,我还是会发布它。
【问题讨论】:
-
看不到难以理解的东西。您已经清楚地找到了
AsyncPipe文档,那么您还需要什么? -
这意味着filteredStates是一个promise或observable,它不会在组件初始化时初始化/定义,并且会在某个未知时间异步解决。并且当它执行时,for循环将运行并显示模板,这与其他可迭代对象(如数组)不同,如果数组未定义或不可用,则会在组件初始化期间抛出错误
标签: angular typescript ngfor