RxJS Angular2 handling 404 in Observable.forkjoin

喜欢而已 提交于 2019-12-10 14:28:54

问题


I'm currently chaining a bunch of http requests, however I am having trouble handling 404 errors before subscribing.

My code:

in template:

...
service.getData().subscribe(
    data => this.items = data,
    err => console.log(err),
    () => console.log("Get data complete")
)
...

in service:

...
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;
    })
}

回答1:


I think you could use the catch operator. The callback you provide when calling it will be called when an error will occur:

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
  });
}



回答2:


This was answered pretty well here: https://stackoverflow.com/a/38061516/628418

In short you put a catch on each observable before you hand them to forkJoin.



来源:https://stackoverflow.com/questions/35592792/rxjs-angular2-handling-404-in-observable-forkjoin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!