【发布时间】:2017-09-25 15:16:48
【问题描述】:
我有一个结构如
的 Json API`{
"type":"champion",
"version":"7.8.1",
"data":
{
"Jax":
{
"id":24,
"key":"Jax",
"name":"Jax",
"title":"o Grão-Mestre das Armas",
"image":
{
"full":"Jax.png",
"sprite":"champion1.png",
"group":"champion",
"x":144,
"y":48,
"w":48,
"h":48
}
}
......`
And I need to tranform this in a Object
My classes for this are this:
`export class Champion{
private type: string;
private version: string;
private data: MasterModel[];
from(data: any): Champion {
this.type = data.type;
this.version = data.version;
this.data = data.data;
return this;
}
}`
`export class MasterModel{
private master: ChampionDto;
from(data: any): MasterModel {
this.master = data.data;
return this;
}
}`
`export class ChampionDto{
constructor(public id: number, public key: string, public name: string, public title: string, public image : ChampionImg){}
from (data: any): ChampionDto {
this.id = data.data.master.id;
this.key = data.data.master.key;
this.name = data.data.master.name;
this.title = data.data.master.title;
this.image = data.data.master.image;
return this;
}
}`
`export class ChampionImg{
constructor(public full: string, public sprite: string, public group: string, public x: number, public y: number, public w: number, public h: number){}
from (data: any): ChampionImg {
this.full = data.full;
this.sprite = data.sprite;
this.group = data.group;
this.x = data.x;
this.y = data.y;
this.w = data.w;
this.h = data.h;
return this;
}
}`
说的对吗?让这些数据放入我的对象的最佳方法是什么? 我在做
--服务
`getChampion(): Observable<Champion> {
return this._http.get(this.riotUrl)
.map((res:Response) => res.json())
.map(res => new Champion().from(res))
.do(data => console.log(JSON.stringify(data)));
}`
--组件
`getData() {
this._ChampionService.getChampion()
.subscribe(data => {
this.champions = data;
})
}`
但不起作用 idk 如果有帮助,但我想做这样的事情 -> http://gameinfo.na.leagueoflegends.com/en/game-info/champions/
有人帮助我吗?谢谢
【问题讨论】:
-
我不认为鸭式打字应该要求您将数据从调用映射到对象,只要它们的结构相同。如果去掉
map(res => new Champion().from(res))行会怎样? -
什么也没发生:/
标签: json api angular object typescript