如何在可观察中按顺序运行订阅

时间:2021-03-25 22:47:34

标签: javascript angular rxjs pipe observable

我想按顺序运行代码,但我想知道这是如何工作的,例如,我有一个包含两个 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 here,我知道这是一个很好的功能来获得我需要的东西,但老实说我不能使用它,只有当我们有 2 个相邻的可观察对象时才有效(只有第 3 步和第 1 步)。

1 个答案:

答案 0 :(得分: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;
      }
    );
}