Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 map http response to instance of class

Tags:

http

angular

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!

like image 558
Growiel Avatar asked Feb 23 '16 09:02

Growiel


1 Answers

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);
}
like image 147
Thierry Templier Avatar answered Oct 18 '22 08:10

Thierry Templier