What is a good practice for conversion response (for e.g. json data) into angular model ? So, in other words how to achieve Auto Mapper functionality in angular 2.
team.service.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; });
}
}
team.data.json
{
"data": [
{"id": "1", "name": "Team 1", "otherProperty" : "S1"},
{"id": "2", "name": "Team 2", "otherProperty" : "S2"},
]
}
team.model.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;
}
}
Method GetAllTeams
should returns Team
objects. I am aware that I can create factory which receive json data and return Array of Team objects, but after reading this article https://angular.io/docs/ts/latest/guide/dependency-injection.html (section car-factory.ts), it seems that it is bad pattern.
Thanks.