我目前正在链接一堆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;
})
}
最佳答案
我认为您可以使用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
});
}