简体   繁体   English

使用 RxJS forkJoin 时传递参数的最佳方式

[英]Best way to pass parameter while using RxJS forkJoin

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!我使用forkJoin是因为我想在收到所有人的回复后采取进一步的行动! 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 ?也许使用RxJS Subject / BehaviorSubject What about RxJS switchMap , can we use it here? RxJS switchMap ,我们可以在这里使用它吗? I am new with RxJS , so be gentle :)我是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();

In this way, you can use your function with the parameter and pass through getDevices method这样,您可以使用带有参数的函数并通过getDevices方法

Also, possible solution using combineLatest and mergeMap for passing id parameter:此外,使用combineLatestmergeMap传递 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 }
    })
  );

You can change id parameter from component like this:您可以像这样从组件更改 id 参数:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM