[英]Best way to pass parameter while using RxJS forkJoin
所以,我有一個服務,它具有我需要執行的三個功能。
我使用forkJoin
是因為我想在收到所有人的回復后采取進一步的行動! 其中之一需要接收一個參數。
getDevices(id: string): Observable<IEquipmentRow[]> {
const url = `${apiUrl}/${id}`;
return this.http.get<IGetDevicesResponse>(url)
.pipe(
map(res => {
return res.data;
})
);
}
private regions$ = this.getRegions();
private devices$ = this.getDevices();
public equipmentPreparationData$ = forkJoin({
regions: this.regions$,
devices: this.devices$
});
實現它的最佳方法是什么? 也許使用RxJS
Subject
/ BehaviorSubject
? RxJS
switchMap
,我們可以在這里使用它嗎? 我是RxJS
的新手,所以要溫柔:)
嘗試:
// Change your response type
public equipmentPreparationData$(deviceID: string): Observable<any> {
return forkJoin({
regions: this.regions$,
devices: this.getDevices(deviceID)
});
private getDevices(id: string): Observable<IEquipmentRow[]> {
const url = `${apiUrl}/${id}`;
return this.http.get<IGetDevicesResponse>(url)
.pipe(
map(res => {
return res.data;
})
);
}
private regions$ = this.getRegions();
這樣,您可以使用帶有參數的函數並通過getDevices
方法
此外,使用combineLatest
和mergeMap
傳遞 id 參數的可能solution
:
public woidSubject: BehaviorSubject<string> = new BehaviorSubject<string>("");
public woidObservable: Observable<string> = this.woidSubject.asObservable();
private devices$ = this.woidObservable.pipe(
mergeMap(x => {
debugger;
return this.getDevices(x);
})
);
public equipmentPreparationData$ = combineLatest([
this.regions$,
this.devices$
]).pipe(
map(([regions, resourceTypes, devices]) => {
return { regions: regions, devices: devices }
})
);
您可以像這樣從組件更改 id 參數:
this.service.woidSubject.next("3243");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.