在使用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$
});

实现这一点的最佳方法是什么?也许用RxJSSubject/BehaviorSubject?那RxJSswitchMap呢,我们可以在这里用它吗?我是RxJS的新手,所以要温柔:)

Try with:

// 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方法

也可能是solution使用combineLatestmergeMap传递id参数:

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");

最新更新