将响应(例如 json 数据)转换为角度模型的良好做法是什么?所以,换句话说,如何在 Angular 2 中实现 Auto Mapper 功能。
团队服务.ts
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { Team } from './team.model';
@Injectable()
export class TeamService {
constructor(private _http: Http) {
}
public GetAllTeams(): Promise<Team[]> {
return this._http.get('/app/teams/shared/team.data.json')
.toPromise()
.then(respons => <Team[]> respons.json().data as Team[])
.then(data => { return data; });
}
}
团队.data.json
{
"data": [
{"id": "1", "name": "Team 1", "otherProperty" : "S1"},
{"id": "2", "name": "Team 2", "otherProperty" : "S2"},
]
}
团队模型.ts
export class Team {
private _id: string;
public get id(): string {
return this._id;
}
public set id(value: string) {
this._id = value;
}
private _name: string;
public get name(): string {
return this._name;
}
public set name(value: string) {
this._name = value;
}
private _icon: string;
public get icon(): string {
return this._icon;
}
public set icon(value: string) {
this._icon = value;
}
}
方法GetAllTeams
应该返回Team
对象。我知道我可以创建接收 json 数据并返回 Team 对象数组的工厂,但是在阅读了这篇文章https://angular.io/docs/ts/latest/guide/dependency-injection.html(部分 car-factory .ts),看来这是不好的模式。谢谢。