Angular rxjs Observable.forkJoin 404

时间:2017-05-15 21:14:18

标签: angular http-status-code-404 observable

我需要做几个不同的服务调用来构建用户对象。其中一个调用并不总是返回数据,因为数据是可选的。

我有下面的代码,但是当遇到可选API调用的404时,代码永远不会进入.map函数。我看到它在可选的URL API调用上遇到了问题,但从未调用.map。是否可以将forkJoin与可能返回404响应的API一起使用?

    return Observable.forkJoin([
        this.wmrk_http.get('required-url')
            .map((res:Response) => <user> res.json())
            .catch((res:Response) =>  Observable.empty<user>()),
        this.wmrk_http.get('required-url-2')
            .map((res:Response) => <groups> res.json())
            .catch((res:Response) =>  Observable.empty<groups>()),
        this.wmrk_http.get('optional-data-url')
            .map((res:Response) => <userData> res.json())
            .catch((res:Response) => Observable.empty<userData>()),     
    ])
    .map((data: any[]) => {
        ...
    });

1 个答案:

答案 0 :(得分:1)

forkJoin stops the chain如果其中一个项目没有发出值。因此,请使用defaultIfEmpty或将observable.empty替换为observable.of(null)。见the working plunker

    Observable.forkJoin([
        this.http.get('https://api.github.com/users/karser')
            .map((res:Response) => res.json())
            .catch((res:Response) =>  Observable.of(null)),
        this.http.get('https://api.github.com/fsdfsdf')
            .map((res:Response) => res.json())
            .catch((res:Response) =>  Observable.of(null)),
        this.http.get('https://api.github.com/2')
            .map((res:Response) => res.json())
            .catch((res:Response) => Observable.of(null))
    ])
    .map((data: any[]) => {
        console.log(data)
    })
    .subscribe();

输出

GET https://api.github.com/users/karser 200 (OK)
GET https://api.github.com/fsdfsdf 404 (Not Found)
GET https://api.github.com/2 404 (Not Found)

[Object, null, null]