【问题标题】:how to run subscribe sequentially in observable如何在 observable 中按顺序运行订阅
【发布时间】:2021-03-25 22:47:34
【问题描述】:

我想按顺序运行代码,但我想知道它是如何工作的,例如,我有一个包含两个可观察字段和一些字段的方法。我想完全运行第一个 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 步。有时它可以正常工作。我读到了concathere,我知道这是一个很好的功能,可以得到我需要的东西,但老实说我不能使用它,而且只有当我们有 2 个可观察的彼此相邻时才有效(只有第 3 步和步骤 1)。

【问题讨论】:

    标签: javascript angular rxjs pipe observable


    【解决方案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;
          }
        );
    }
    

    【讨论】:

    • 感谢分享,我知道通过 switchMap 我们可以取消订阅第一个请求,通过点击我们可以说之后的内容,不是吗?只有一个小费。超过 3 步怎么样,例如在第 4 步中我们有另一个 oberable 或请求。我们可以使用带有 3 个或更多请求的 switchMap 吗?
    • 是的,您可以根据需要保留额外的操作员。因此,如果第 4 步返回一个 observable,您可以通过管道输入一个额外的 switchMap
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-23
    • 2020-07-03
    • 1970-01-01
    • 1970-01-01
    • 2018-09-01
    相关资源
    最近更新 更多