Angular 2 map http response to instance of class

后端 未结 3 705
鱼传尺愫
鱼传尺愫 2021-02-19 05:57

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

相关标签:
3条回答
  • 2021-02-19 06:32

    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.

    0 讨论(0)
  • 2021-02-19 06:42

    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

    0 讨论(0)
  • 2021-02-19 06:45

    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);
    }
    
    0 讨论(0)
提交回复
热议问题