如何解决如何在可观察中按顺序运行订阅
我想按顺序运行代码,但我想知道这是如何工作的,例如,我有一个包含两个 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 步)。
解决方法
没有足够的数据可供参考,但首先您可以使用 tap
和 switchMap
运算符。 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;
}
);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。