我目前正在链接一堆http请求,但是在订阅之前我无法处理404错误。
我的代码:
模板中的:
...
service.getData().subscribe(
data => this.items = data,
err => console.log(err),
() => console.log("Get data complete")
)
...
在服务中:
...
getDataUsingUrl(url) {
return http.get(url).map(res => res.json());
}
getData() {
return getDataUsingUrl(urlWithData).flatMap(res => {
return Observable.forkJoin(
// make http request for each element in res
res.map(
e => getDataUsingUrl(anotherUrlWithData)
)
)
}).map(res => {
// 404s from previous forkJoin
// How can I handle the 404 errors without subscribing?
// I am looking to make more http requests from other sources in
// case of a 404, but I wouldn't need to make the extra requests
// for the elements of res with succcessful responses
values = doStuff(res);
return values;
})
}
答案 0 :(得分:3)
我认为您可以使用catch
运算符。调用它时提供的回调将在发生错误时被调用:
getData() {
return getDataUsingUrl(urlWithData).flatMap(res => {
return Observable.forkJoin(
// make http request for each element in res
res.map(
e => getDataUsingUrl(anotherUrlWithData)
)
)
}).map(res => {
// 404s from previous forkJoin
// How can I handle the 404 errors without subscribing?
// I am looking to make more http requests from other sources in
// case of a 404, but I wouldn't need to make the extra requests
// for the elements of res with succcessful responses
values = doStuff(res);
return values;
})
.catch((res) => { // <-----------
// Handle the error
});
}
答案 1 :(得分:3)
这里答案非常好:https://stackoverflow.com/a/38061516/628418
简而言之,在你将它们交给forkJoin之前,你会在每个observable上放一个catch。