gpt4 book ai didi

Angular :捕获 rxjs 管道/合并映射序列中的错误

转载 作者:太空狗 更新时间:2023-10-29 17:56:35 26 4
gpt4 key购买 nike

目前我的代码结构如下,并且运行良好:

// service:
getRequestA() { return this.http.get(someUrl) }
getRequestB(id) { return this.http.get(someUrl + id) }
getRequestC(id) { return this.http.get(someUrl + id) }
getAll() {
return getRequestA()
.pipe(
mergeMap((resp) => {
return this.getRequestB(resp.id)
}),
mergeMap((resp) => {
return this.getRequestC(resp.id)
})
)
}

这允许我在我的组件中执行此操作:

// component:
service.getAll().subscribe(resp => {
// result of service.getRequestC()
}, error => {
// error occurred in any 1 of the 3 http calls
});

这很棒,因为我需要每次调用的结果才能触发下一次调用,而且我只关心最终结果。但是,现在我想知道 3 个 http 调用中具体是哪一个失败了,以便向用户显示更好的错误。我已经尝试了很多东西,但无法弄清楚在服务中抛出自定义错误,然后我可以在组件中区分这些错误。提前感谢您的任何建议!

最佳答案

像这样的安排应该让你标记并重新抛出任何错误:

const tagError = (tag, error) => {
error.tag = tag;
return error;
};

getAll() {
return getRequestA().pipe(
catchError(error => { throw tagError("A", error); }),
mergeMap(resp => this.getRequestB(resp.id).pipe(
catchError(error => { throw tagError("B", error); })
)),
mergeMap(resp => this.getRequestC(resp.id).pipe(
catchError(error => { throw tagError("C", error); })
))
);
}

事实上,您可以更进一步,将 tagError 函数变成一个管道运算符:

const tagError = tag => catchError(error => {
error.tag = tag;
throw error;
});

getAll() {
return getRequestA().pipe(
tagError("A"),
mergeMap(resp => this.getRequestB(resp.id).pipe(tagError("B"))),
mergeMap(resp => this.getRequestC(resp.id).pipe(tagError("C")))
);
}

关于 Angular :捕获 rxjs 管道/合并映射序列中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48715591/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com