So I finally decided to catch up with the times and migrate some old angular Http
stuff to HttpClient
.
The app used to run on a bunch of Promise based code, which has since been removed (mostly).
My old Promise function looked something like this:
public getUser(profileId: number): Promise<User> {
return this.http.post("/api/url", postObject, HttpSettings.GetDefaultHttpRequestOptions());
.map(u => new User(u))
.catch(this.handleError)
.toPromise();
}
My new HttpClient function is much nicer:
public getUser(profileId: number): Observable<any> {
return this.http.post("/api/url", postObject, HttpSettings.GetDefaultHttpRequestOptions());
}
But what I don't like currently is that in each subscription to this, I now have to map the data to an instance of User...
service.getUser(1).subscribe(data => {
data = new User(data);
});
This is the simplest .map
which I have, some post methods actually return a rather complex object which map to many new object instances.
I see with HttpClient.get
you can Type assert the response, can I do something like this with .post
so that I don't have to map the data to a new User in each of the subscriptions?
Note: Eventually I will migrate this again to a better architecture where you actually subscribe to a User variable, but for now I just want to implement HttpClient.
can I do something like this with .post so that I don't have to map the data to a new User in each of the subscriptions
<= Yes, the exact same generic to specify the return type is available forpost
and alsoput
. It will not convert automatically to an object but you can specify an interface for the returned data. Alternatively you can chainmap
in the service like you did previously. – Sensory