问题
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.
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_);
});
}
For this question it doesn't matter what getResponse
and MyResponseClass
they are, so I'll skip to explain that.
Ok, so the first step is changing .flatMap to .pipe() and map() because of that:
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:
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.
Will you help me with that?
回答1:
Your RxJS
is most probably updated from v5.x to v6.x. Therefore you need to refactor your code which involves RxJS
.
Here is the update guide:
https://github.com/ReactiveX/rxjs/blob/master/docs_app/content/guide/v6/migration.md
回答2:
Aa per rxjs V6 Update Guide chaining operators has been replaced by piping
also catch
changed to catchError
so your final code should be
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_);
})
);
Or you can use rxjs-compact
来源:https://stackoverflow.com/questions/54438854/how-to-change-httpclient-code-after-update-app-to-angular-7