I\'m wondering what the best way is to map the http response from a get request to a class instead of a basic Javascript object.
In my current attempt I simple do
Good practice is to consume data from GET response using
Observable<Model>
(regarding to Angular documentation https://angular.io/guide/http) So...
// imports
import {HttpClient} from "@angular/common/http";
// in constructor parameter list
private http: HttpClient
// service method
getHeroes(): Observable<Hero[]> {return this.http.get<Hero[]>({url}, {options});}
You do not need to do anything more. I consider this approach as most friendly.
By setting the prototype on the object being returned I was able to get an instance of my class.
getHero () {
return this.http.get(this._heroUrl)
.map(response => {
let res = <Hero> response.json();
Object.setPrototypeOf(res, Hero.prototype);
return res;
})
.catch(this.handleError);
}
My class was very simple with a parameterless constructor so this worked for me. For more complex classes I don't know if this would work.
Note: the above code is for getHero() not getHeroes(). I would assume I could do the same thing with a list by setting the prototype on each item in the array but I haven't tried/confirmed that.
Reference: I got the idea for this from this post by BMiner
I think that you could use the map
method of JavaScript objects:
getHeroes () {
return this.http.get(this._heroesUrl)
.map(res => {
return res.json().data.map((elt) => {
// Use elt to create an instance of Hero
return new Hero(...);
});
})
.catch(this.handleError);
}