Home > Software design >  Best way to pass parameter while using RxJS forkJoin
Best way to pass parameter while using RxJS forkJoin

Time:05-24

So, I have a service that has three functions that I need to execute.

I use forkJoin because I want to take further action when a response has been received for all! One of them needs to receive one parameter.

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

What is the best way to implement that? Maybe using RxJS Subject/BehaviorSubject? What about RxJS switchMap, can we use it here? I am new with RxJS, so be gentle :)

CodePudding user response:

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

In this way, you can use your function with the parameter and pass through getDevices method

CodePudding user response:

Also, possible solution using combineLatest and mergeMap for passing id parameter:

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

You can change id parameter from component like this:

this.service.woidSubject.next("3243");
  • Related