RxJS Angular2 在 Observable.forkjoin 中处理 404

2024-05-03

我目前正在链接一堆 http 请求,但是在订阅之前我无法处理 404 错误。

My code:

在模板中:

...
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
  });
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

RxJS Angular2 在 Observable.forkjoin 中处理 404 的相关文章

随机推荐