如何 运行 在 observable 中顺序订阅

how to run subscribe sequentially in observable

我想 运行 按顺序编码,但我想知道它是如何工作的,例如,我有一个方法包含两个可观察对象和一些字段。我想 运行 第一个 observable 完全然后检查下一个字段值,然后是最后一个 observable 方法:

// first it should be run completely --Step1

ontemplateSelectChanged(e){
const api = 'api/Sales/SaleTemplate/' + e;
this.dataSourceService
      .generateCustomApiDataList('sales', 'SaleTemplate', api)
      .dataList$.subscribe(
        (data) => {
this.saleTemplateDsDto.saleTemplateDto = data.rows['saleTemplateDto'];
});
// 2nd this should be check --step 2
if (myCondition){
// a lot of code here
    alert("we are here")
    }
    // this should be run at the end. --step 3
     const additionApi =
            'api/Sales/Addition/List?$filter=AdditionCode eq ' +
            additionCodefilterValue;
          this.dataSourceService
            .generateCustomApiDataList('sales', 'Addition', additionApi)
            .dataList$.subscribe(
              (data) => {            
                additionDtoList = data.rows;})
    }

但在当前阶段,第 2 步先完成,然后第 3 步和第 1 步结束。有时它工作正常。我读到 concat ,我知道这是一个很好的功能,可以满足我的需要,但老实说,我无法使用它,而且只有当我们有 2 个彼此相邻的可观察对象时,它才有效(只有第 3 步和第 1 步)。

没有足够的数据可供使用,但首先您可以使用 tapswitchMap 运算符。 tap 将用于“第 2 步”,switchMap 将用于映射到另一个可观察对象(在您的情况下是“第 3 步”,即第二个 HTTP 请求)。

尝试以下方法

import { switchMap, tap } from 'rxjs/operators';

ontemplateSelectChanged(e) {
  const api = 'api/Sales/SaleTemplate/' + e;
  this.dataSourceService
    .generateCustomApiDataList('sales', 'SaleTemplate', api)
    .dataList$
    .pipe(
      tap((data: any) => {
        this.saleTemplateDsDto.saleTemplateDto = data.rows['saleTemplateDto'];
        if (myCondition) {
          // a lot of code here
          alert("we are here")
        }
      }),
      switchMap(() => {
        const additionApi =
          'api/Sales/Addition/List?$filter=AdditionCode eq ' +
          additionCodefilterValue;
        return this.dataSourceService
          .generateCustomApiDataList('sales', 'Addition', additionApi)
          .dataList$;
      })
    ).subscribe(
      (data) => {
        additionDtoList = data.rows;
      }
    );
}