嵌套订阅并需要所有值作为正文传递给 API - Angular 6 RxJS

Nested subscribe and need all values to pass as body to API - Angular 6 RxJS

我正在开发一个 table 组件,table 组件的数据将根据三个下拉值填充。我需要将所有三个值传递给 API 以获得所需的响应。我可以使用嵌套订阅来实现它,这是一种非常糟糕的方式。但是任何更改都会多次调用 API 。我该如何解决?我发现的大多数示例仅用于获取最终订阅值,但就我而言,我需要所有三个。使用 tapflatMap 有什么建议吗?

请指教

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

这是我的 dataService 的示例。我在 table 组件的构造函数中将我的 dataservice 初始化为 _data.

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

    private changeGroupData = new BehaviorSubject<string>('');
    currentChangeGroup = this.changeGroupData.asObservable();

您可以使用combineLatest组合三个Observable,然后一次订阅所有的Observable。一旦三个 Observable 之一发生变化,它就会发出一个新值。

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

举个例子,看看我创建的这个 stackblitz demo