在此代码示例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。:-)
有用的链接:
https://angular.io/api/forms/FormControl for FormControl.valueChanges
我尚未从FormControl.valueChanges中找到如何使用管道,但希望在回答此问题时这将变得清楚。
(Q)谁能指出我一些解释“ * ngFor | async”语法含义的Angular文档?或提供解释。
搜索答案显示了这些结果
在ngFor和Async Pipe Angular 2中使用来自Observable Object的数组-我认为我遇到的问题是相似的,但是我读了这个答案,但没有解释,只有代码示例。
https://blog.thoughtram.io/angular/2017/02/27/three-things-you-didnt-know-about-the-async-pipe.html-这似乎是我问题的答案。但是,由于我花了很多时间进行写作,所以我仍然会发布它。
该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] 删除。
我来说两句