RxJS Angular2在Observable.forkjoin中处理404

ray*_*ray 5 http fork-join observable rxjs angular

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

我的代码:

在模板中:

...
service.getData().subscribe(
    data => this.items = data,
    err => console.log(err),
    () => console.log("Get data complete")
)
...
Run Code Online (Sandbox Code Playgroud)

在服务中:

...
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;
    })
}
Run Code Online (Sandbox Code Playgroud)

Thi*_*ier 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
  });
}
Run Code Online (Sandbox Code Playgroud)