Angular 2 map http response to instance of class

后端 未结 3 710
鱼传尺愫
鱼传尺愫 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: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 =  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

提交回复
热议问题