After much consideration, I decided to update some outdated Angular Http
code to use HttpClient
.
The app used to rely on Promise-based code, which has now been mostly removed. Here's a snippet of my old Promise function:
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 cleaner:
public getUser(profileId: number): Observable<any> {
return this.http.post("/api/url", postObject, HttpSettings.GetDefaultHttpRequestOptions());
}
However, one thing that bothers me now is having to map the data to a User instance in every subscription:
service.getUser(1).subscribe(data => {
data = new User(data);
});
This example shows a simple .map
, but there are cases where post methods return complex objects that need to be mapped to multiple instances.
I noticed that with HttpClient.get
you can Type assert the response. Is it possible to do something similar with .post
so that I don't have to manually map the data in each subscription?
Note: While I plan to eventually migrate to a better architecture where users subscribe to a User variable, for now I just want to implement HttpClient.