我已经定义了一个behaviorSubject:
measurementSearchChange$ = new BehaviorSubject('');
this.measurementSearchChange$
.asObservable()
.pipe(debounceTime(500))
.pipe(
switchMap((keyword: string) =>
this.warningService.getInfluxdbQuery(
this.selectedMonitorOption,
'measurement',
{ search_name: keyword }
)
)
)
.subscribe((data: any) => {
this.measurementOptions = data;
this.isLoading = false;
});
执行某些操作时会这样做:
this.measurementSearchChange$.next(keyword);
它现在工作良好,但是我想添加一个switchMap并压缩它们,以便我可以订阅两个不同的数据,例如:
this.measurementSearchChange$
.asObservable()
.pipe(debounceTime(500))
.pipe(
switchMap((keyword: string) =>
this.warningService.getInfluxdbQuery(
this.selectedMonitorOption,
'measurement',
{ search_name: keyword }
)
// another
this.warningService.getInfluxdbQuery2(
this.selectedMonitorOption,
'measurement2',
{ search_name: keyword }
)
)
)
.subscribe((data1: any, data2: any) => {
this.measurementOptions = data;
this.isLoading = false;
});
那怎么办呢?任何帮助都感激
答案 0 :(得分:1)
如果查询发出单个结果然后完成,则可以使用forkJoin
,如下所示:
import { forkJoin } from 'rxjs';
/* ... */
this.measurementSearchChange$
.asObservable()
.pipe(
debounceTime(500),
switchMap((keyword: string) => forkJoin(
this.warningService.getInfluxdbQuery(
this.selectedMonitorOption,
'measurement',
{ search_name: keyword }
),
this.warningService.getInfluxdbQuery2(
this.selectedMonitorOption,
'measurement2',
{ search_name: keyword }
)
))
)
.subscribe(([data1, data2]: [any, any]) => {
this.measurementOptions = data;
this.isLoading = false;
});
如果它们发出多个结果,请使用combineLatest
而不是forkJoin
。
我不会使用zip
,除非在这种情况下查询可以发出多个结果,并且可以保证每次一个查询发出结果时另一个查询也将发出一个结果。