在其中一个错误发生后中断顺序concatMap调用



我的程序中有一个视图,其中的数据是分层的,所以我需要对数据库进行连续调用,以便填充适当的数据结构并显示视图,如果其中一个调用失败,我想要中断它们。

我是Angular的新手,所以我在网上研究了很多,发现嵌套订阅是一个不好的做法,应该避免,所以我使用了concatMap。现在,在预览失败后,我如何中断concatMaps的序列?

这是我的代码:

getData() {        
this.service.httpCall(null,
url + '/test/getallprovinces').pipe(
tap( (responsePro) => {
if (responsePro.type === 'success') {
//fill in data structures
} else {
//handle error and interrupt
throwError("error ");
}}),
concatMap(() => this.service.httpCall(null, url + '/test/getallcantons')),
tap((responseCanton) => {
if (responseCanton.type === 'success') {
//fill in data structures
} else {   
//handle error  and interrupt               
throwError("error on cantons");
}
}),
concatMap(() => this.service.httpCall(null, url + '/test/getalldistricts')),
tap(responseDis => {
if (responseDis.type === 'success') {
//fill in data structures
} else {
//handle error  and interrupt
throwError("error on districts");
}
}))
.subscribe(
() => {},
error => {console.log("something happened", error)}
);
}

现在如果发生错误,它会跳转到下一个concatMap调用,因为没有数据,它会尝试填充数据结构,并在那里抛出一个丑陋的错误(推入空数组)。我想使用trhowError

中断调用编辑:我已经找到了解决方案,这在一定程度上要感谢Joshua McCarthy。我使用的是返回一个可观察对象并继续执行的throwError。相反,我应该在tap中抛出一个普通的旧JS异常。现在它中断了高阶可观察对象。

尝试在管道末端添加catchError()。在那里,您可以打印到控制台日志并返回EMPTY。这会在发出错误通知的那一刻中断可观察链。

最新更新