假设在我的 Component 中我有一个 Observable
字段,它是通过 Service 检索的,它使用 HttpClient
@Component(...)
export class MyComponent {
items$: Observable<readonly Item[]>;
ngOnInit() {
this.items$ = this.findItems();
}
private findItems() {
return this.service
.getItems(...)
.pipe(
// Other code omitted
toArray<Item>()
);
}
}
<app-items [items]="items$ | async"></app-items>
然后,当在 MyComponent
中执行操作时,我需要刷新 items$
列表,因此我调用了 Service
onButtonPressed() {
this.items$ = this.findItems();
}
问题是,Async
管道会自动订阅新的 Observable
吗?
考虑到我采用的是 OnPush
策略,是否需要请求 detectChanges()
?
最重要的是,这是正确的方法吗?
最佳答案
您可能想要使用 switchMap
管道:
@Component(...)
export class MyComponent {
items$: Observable<readonly Item[]>;
updater$: Subject<void> = new Subject<void>();
ngOnInit() {
this.items$ = this.updater$
.pipe(
switchMap<void, Observable<Items[]>>(() => this.findItems())
)
}
onButtonPressed(){
this.updater$.next();
}
private findItems() {
return this.service
.getItems(...)
.pipe(
// Other code omitted
toArray<Item>()
);
}
}
并且仍然使用:
<app-items [items]="items$ | async"></app-items>
switchMap()
允许您拥有一个“永不重新分配”的可观察对象(updater$
),并且对于此流上的每个发射度,它“切换”可观察对象的发射值以发送内部函数的结果,这应该是一个可观察对象.
在这里,每次调用updater$.next()
,它“切换”发射的 void
findItems()
的结果方法,这是您的项目数组。
switchMap
之间的区别和 mergeMap
是那个switchMap
负责完成和关闭之前发出的可观察对象。如果您调用 updater$.next()
两次,第二次调用switchMap
将完成第一次调用 findItems()
返回的第一个可观察对象并用此方法的新调用替换它。
来源:
https://www.learnrxjs.io/operators/transformation/switchmap.html
https://blog.angular-university.io/rxjs-higher-order-mapping/
关于angular - 重新分配通过异步管道使用的 Observable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55968247/