rxjs - 组合 combineLatest 和 switchMap 时未定义
问题描述
我正在尝试将两个 Observable 组合起来,以便为接受两个值的服务调用方法提供很少的值。但在这里我有几个错误
'([filter, sort]: [string, string]) => void' 类型的参数不能分配给 '(value: [string, string], index: number) => ObservableInput' 类型的参数。类型“void”不可分配给类型“ObservableInput”。
在控制台中 -
您在预期流的位置提供了“未定义”。您可以提供 Observable、Promise、Array 或 Iterable。在 subscribeTo (subscribeTo.js:27) 在 innerSubscribe (innerSubscribe.js:71) 在 SwitchMapSubscriber._innerSub (switchMap.js:44) 在 SwitchMapSubscriber._next (switchMap.js:34) 在 SwitchMapSubscriber.next (Subscriber.js:49 ) 在 CombineLatestSubscriber.notifyNext (combineLatest.js:73) 在 InnerSubscriber._next (InnerSubscriber.js:11) 在 InnerSubscriber.next (Subscriber.js:49) 在 BehaviorSubject._subscribe (BehaviorSubject.js:14) 在 BehaviorSubject._trySubscribe ( Observable.js:42)
定义 Observables 和 Subjects。
private openSortQuerySubject: BehaviorSubject<string> = new BehaviorSubject<string>(this.formatSortQuery(this.multiSortMeta)); public openSortQuery: Observable<string> = this.openSortQuerySubject.asObservable(); private closedSortQuerySubject: BehaviorSubject<string> = new BehaviorSubject<string>(this.formatSortQuery(this.multiSortMeta)); public closedSortQuery = this.closedSortQuerySubject.asObservable();
结合可观察的。
const openQueries$ = combineLatest([this.openFilterQuery, this.openSortQuery]); const closedQueries$ = combineLatest([this.closedFilterQuery, this.closedSortQuery]);
在服务方法中使用合并值。
openQueries$
.pipe(
switchMap(([filter, sort]) => {
this.alertService
.listAlerts(filter, sort);
}),
tap(v => console.log(v))
)
.subscribe((openAlerts) => {
this.openAlertsCount = openAlerts.length;
this.openAlerts = this.parseAlerts(openAlerts);
});
closedQueries$
.pipe(
switchMap(([filter, sort]) => {
this.alertService
.listAlerts(filter, sort);
})
)
.subscribe((closedAlerts) => {
this.closedAlertsCount = closedAlerts.length;
this.closedAlerts = this.parseAlerts(closedAlerts);
});
解决方案
你必须在回调中返回一个 observable(或者 RxJS 知道如何变成 observable 的东西)switchMap
。
不是这个:
switchMap(([filter, sort]) => {
this.alertService.listAlerts(filter, sort);
})
但是这个(假设listAlerts
返回一个可观察的,一个承诺或类似的):
switchMap(([filter, sort]) => {
return this.alertService.listAlerts(filter, sort);
})
推荐阅读
- javascript - Html web worker 没有按预期工作
- angular - FormData 未进入 API 控制器的 Post 方法
- php - 带 GPS 路线的数据库
- google-app-maker - 在 Appmaker 中显示数据源总页数的最佳方式
- php - 内联 CSS 不适用于 Mpdf
- ios - tableView 滚动到最新单元格的底部 - scrollToRow() 的问题
- c# - 如何使用多线程c#执行控制台应用程序
- ios - 如何弱引用作为参数传递的函数
- python - 控制 df.at 或 df.loc 的行为
- python - 从 Python 中的列表创建元组列表