Angular 2映射http响应类的实例 [英] Angular 2 map http response to instance of class
问题描述
我想知道最好的方法是将来自get请求的http响应映射到类而不是基本的Javascript对象。
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.
在我当前的尝试中我简单地做了新的ClassName(数据)
,但是可能有一个模糊的Angular指定和完全令人敬畏的方式,我不知道。
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.
这是我目前的代码:
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);
}
我需要Post作为一个类而不仅仅是一个接口,因为我有方法内部。
I need Post to be a class and not just an interface because I have methods inside.
我按照HeroTutorial和http开发人员指南进行了他们的 getHeroes
方法:
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);
}
我不知何故预期< Hero []> ;
这样做的部分:拿Hero类并创建它的新实例,但我的测试表明它没有,这几乎只是Typescript知道会发生什么。
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.
任何想法?谢谢!
推荐答案
我认为您可以使用 map
方法JavaScript对象:
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);
}
这篇关于Angular 2映射http响应类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!