2

I am developing a table component and the data for the table component is to be populated on basis of three dropdown values. I need to pass in all three values to the API to get the desired response. I can achieve it using nested subscribes, which is a very bad way. but any change calls the API multiple times. How can I fix it? Most examples I found are for getting only the final subscribe value but in my case, I need all three. Any advice to achieve using tap and flatMap?

Please advice.

    this._data.currentGroup.subscribe(bg => {
        this.bg = bg;

        this._data.currentUnit.subscribe(bu => {
            this.bu = bu;

            this._data.currentFunction.subscribe(jf => {
                this.jf = jf;

                this.apiService.getFunctionalData(this.bg, this.bu, this.jf)
                .subscribe(
                  (data) => {
                    console.log(data)
                  }
                );

            });
        });
    });

This is what I did.

    this._data.currentGroup.pipe(
        tap(bg => this.bg = bg),
        flatMap(bu => this._data.currentUnit.pipe(
            tap(bu => this.bu = bu),
            flatMap(jf => this._data.currentFunction.pipe(
                tap(jf => this.jf = jf)
            ))
        ))
    ).subscribe();

This is a sample example of my dataService. I initialize my dataservice in the table component's constructor as _data.

    changeGroup(bg: string) {
      this.changeGroupData.next(bg);
    }

    private changeGroupData = new BehaviorSubject<string>('');
    currentChangeGroup = this.changeGroupData.asObservable();
Kim Kern
  • 54,283
  • 17
  • 197
  • 195
arunmmanoharan
  • 2,535
  • 2
  • 29
  • 60

1 Answers1

1

You can use combineLatest to combine the three Observables and then subscribe to all of them at once. It will emit a new value as soon as one of the three Observables changes.

combineLatest(this._data.currentGroup,
              this._data.currentUnit,
              this._data.currentFunction).subscribe(([bg, bu, jf]) => {
        // do stuff
      });

For an example, have a look at this stackblitz demo I created.

Kim Kern
  • 54,283
  • 17
  • 197
  • 195