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 new ClassName(data)
, but there might an obscure Angular specify and completely awesome way to do this that I don't know.
Here's my current code:
getPost(id:number){
return this._http.get(this._postsUrl+'/'+id)
.map(res => new Post(res.json().data))
.do(data => console.log(data))
.catch(this.handleError);
}
I need Post to be a class and not just an interface because I have methods inside.
I followed the HeroTutorial and the http "developer guide" along and in their getHeroes
method they do:
getHeroes () {
return this.http.get(this._heroesUrl)
.map(res => <Hero[]> res.json().data)
.catch(this.handleError);
}
I somehow expected the <Hero[]>
part to do just that: Take the Hero class and create new instances of it, but my tests show that it doesn't, this is pretty much just for Typescript to know what to expect.
Any ideas ? Thanks!