如何在将应用程序更新到 Angular 7 后更改 HttpClient 代码

How to change HttpClient code after update app to Angular 7

我将 Angular 更新到我的应用程序中的版本 7,更新后我必须稍微更改我的代码,但我不确定该怎么做。

这是要更改的代码示例(在 Angular 的先前版本中):

get(): Observable<MyResponseClass | null> {
    let url_ = some_url;

    let options_: any = {
        method: "get",
        headers: new Headers({
            "Content-Type": "application/json",
            "Accept": "application/json"
        })
    };

    return this.http.request(url_, options_).flatMap((response_: any) => {
        return this.getResponse(response_);
    }).catch((response_: any) => {
        if (response_ instanceof Response) {
            try {
                return this.getResponse(<any>response_);
            } catch (e) {
                return <Observable<MyResponseClass | null>><any>Observable.throw(e);
            }
        } else
            return <Observable<MyResponseClass | null>><any>Observable.throw(response_);
    });
}

对于这个问题,getResponseMyResponseClass是什么并不重要,所以我会跳过解释。

好的,所以第一步是将 .flatMap 更改为 .pipe() 和 map() 因为:

Property 'flatMap' does not exist on type Observable<Object>.

所以在这次更改之后我的代码看起来像这样:

return this.http.request(url_, options_).pipe(map((response_: any) => { 
            return this.getResponse(response_); })
        ).catch((response_: any) => {
            if (response_ instanceof Response) {
                try {
                    return this.getResponse(<any>response_);
                } catch (e) {
                    return <Observable<MyResponseClass | null>><any>Observable.throw(e);
                }
            } else
                return <Observable<MyResponseClass | null>><any>Observable.throw(response_);
        });

现在我遇到了这样的错误:

Property 'catch' does not exist on type 'Observable<Observable<MyResponseClass>>'.

这里我遇到了问题,因为我真的不知道应该如何更改它。我仍在寻找有关 google 和堆栈溢出的一些信息,但尚未成功。可能是我了解的不够多。

你能帮我吗?

您的 RxJS 很可能已从 v5.x 更新为 v6.x。因此,您需要重构涉及 RxJS.

的代码

这里是更新指南:

https://github.com/ReactiveX/rxjs/blob/master/docs_app/content/guide/v6/migration.md

Aa per rxjs V6 Update Guide chaining operators has been replaced by pipingcatch 更改为 catchError 所以你的最终代码应该是

  return this.http.request(url_, options_).pipe(map((response_: any) => { 
                return this.getResponse(response_); }),
              catchError((response_: any) => {
                if (response_ instanceof Response) {
                    try {
                        return this.getResponse(<any>response_);
                    } catch (e) {
                        return <Observable<MyResponseClass | null>><any>Observable.throw(e);
                    }
                } else
                    return <Observable<MyResponseClass | null>><any>Observable.throw(response_);
            })
            );

或者您可以使用 rxjs-compact