将应用程序更新到 Angular 7 后如何更改 HttpClient 代码 [英] How to change HttpClient code after update app to Angular 7
问题描述
我将 Angular 更新到了我的应用程序中的第 7 版,更新后我必须稍微更改我的代码,但我不知道该怎么做.
I updated Angular to version 7 into my app and I have to change my code a little bit after update but I'm not sure how to do it.
这是要更改的代码示例(在以前的 Angular 版本中):
This is example of code to change (in previous version of 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_);
});
}
对于这个问题,getResponse
和 MyResponseClass
是什么并不重要,所以我将跳过解释.
For this question it doesn't matter what getResponse
and MyResponseClass
they are, so I'll skip to explain that.
好的,因此第一步是将 .flatMap 更改为 .pipe() 和 map() :
Ok, so the first step is changing .flatMap to .pipe() and map() because of that:
Observable
Property 'flatMap' does not exist on type Observable<Object>.
因此在此更改后,我的代码如下所示:
So after this change my code looks like that:
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_);
});
现在我遇到了这样的错误:
And now I've got the error like that:
Observable
Property 'catch' does not exist on type 'Observable<Observable<MyResponseClass>>'.
这里我遇到了问题,因为我真的不知道我应该改变它.我仍在寻找谷歌和堆栈溢出的一些信息,但还没有成功.可能我对这方面的了解还不够.
And here I've got the problem because I really don't know what I should to change it. I'm still looking for some information into google and stack overflow but without success yet. Maybe I haven't enough knowladge of that.
你会帮助我吗?
推荐答案
您的 RxJS
很可能已从 v5.x 更新到 v6.x.因此,您需要重构涉及 RxJS
的代码.
Your RxJS
is most probably updated from v5.x to v6.x. Therefore you need to refactor your code which involves RxJS
.
这是更新指南:
https://github.com/ReactiveX/rxjs/blob/master/docs_app/content/guide/v6/migration.md
这篇关于将应用程序更新到 Angular 7 后如何更改 HttpClient 代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!