angular - Interrupt sequential concatMap calls after error happens in one of them
问题描述
I have a view in my program with data that's hierarchical, so I need to do secuencial calls to the data base in order to fill in the appropiate data structures and show the view, if one of these calls fail I want to interrupt them.
I'm new to Angular so I researched a lot on the internet and found out that nested subscribes are a bad practice and should be avoided, so I used concatMap. Now, how do I interrupt the secuence of concatMaps after the preview one fails?
This is my code:
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)}
);
}
Right now if an error happens it jumps to the next concatMap call and since there's no data it tries to fill the data structues and throws an ugly error there (pushing to an empty arra). I want to interrupt the call using trhowError
Edit: I've found the solution thanks in part to Joshua McCarthy. I was using throwError
that returns an observable and continues execution. Instead I should've trhown a plain old JS exception inside the tap
. Now it does interrupt the higher-order observables.
解决方案
Try to add catchError()
at the end of the pipe. There you can print to console log and return EMPTY
. This should interrupt the observable chain the moment am error notification is emitted.
推荐阅读
- html - Angularjs动态添加的行文本值没有得到
- r - 用 ' 分割字符串' 在 R 中
- python - 在python中定位大型数据集中的多个文件
- r - 自定义图例,引入未绘制但通过 geom_label 汇总的变量
- postgresql - UPDATE 查询中的 FROM 后的 Postgres 语法错误
- javascript - 使用 jquery-ui 将 ajax 添加到现有页面
- angular - 数据值更改时如何自动更新地理图表(来自 angular2 谷歌图表)?
- c# - 验证没有电子邮件/用户 ID 的密码重置令牌
- python - 如何在 pyqt 信号上使用装饰器?
- python - 调用其他方法的python unittest方法