【问题标题】:RxJS Angular2 handling 404 in Observable.forkjoinRxJS Angular2 在 Observable.forkjoin 中处理 404
【发布时间】:2016-02-24 03:40:05
【问题描述】:

我目前正在链接一堆 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;
    })
}

【问题讨论】:

    标签: http angular observable rxjs fork-join


    【解决方案1】:

    我认为您可以使用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
      });
    }
    

    【讨论】:

    • 谢谢! catch 解决了我的问题,但是要在 forkJoin 调用期间单独处理每个错误,我需要在 getDatausingUrl 方法中捕获错误。
    • @Thierry Templier 我有一些类似的问题。在我的 forkjoin 中运行的三个查询之一返回 404。我发现了错误,但它阻止了我获取其他两个查询的结果。好像整个过程都停止了。关于导致这种行为的任何想法?谢谢!
    • 好的,谢谢,使用this S.O question解决了。
    【解决方案2】:

    这里的回答很好:https://stackoverflow.com/a/38061516/628418

    简而言之,在将每个 observable 交给 forkJoin 之前,您先对它们进行捕获。

    【讨论】:

      猜你喜欢
      • 2016-03-17
      • 1970-01-01
      • 2016-11-05
      • 2016-07-17
      • 1970-01-01
      • 2017-12-25
      • 2017-08-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多