这在此代码示例中使用 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 循环可能会在 Observable 上循环,因为 Async 管道接受 Promise 或 Observable,而不是 Promise。 :-)
有用的链接:
我一直无法从 FormControl.valueChanges 中找到管道是如何使用的,但希望在回答这个问题时这会变得清楚。
(Q) 有人能给我指点一下解释“*ngFor | async”语法是什么意思的 Angular 文档吗?或提供解释。
搜索答案显示了这些结果
最佳答案
let state of filteredStates | async
语法可以被认为是这样的:
let state of (filteredStates | async)
async
管道适用于filteredStates
变量而不是整个 for
环形。我认为在查看您查看的所有其他资源后应该很明显,但是
async
pipe 很有用,因为它会为您订阅 observable(并另外清理订阅,因此您无需担心取消订阅)。所以,发生的事情是 Angular 订阅了你的
filteredStates
可观察的。每次从您的 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;
}
}
}
关于angular - 在 Angular 中,*ngFor ="let item from list | async"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49546749/