Angular 2 - good practice during conversion response into angular model

723 views Asked by At

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.

1

There are 1 answers

1
Jecfish On

Actually, you don't need to create a class as model if what you need is strong typing. You can use Interface instead.

export interface Team {
    id: string;
    name: string;
    icon: stirng;
    someOtherProperty: [];
}

The benefit of using Interface is that you get strong typing while there's no code generated for interface while class will generate extra code.

The way you do the response conversion now I think is good, IMHO.

public GetAllTeams(): Promise<Team[]> {
    return this._http.get('/app/teams/shared/team.data.json')
                .toPromise()
                .then(respons => respons.json())
                .then(x => x.data);
}

Always remember TypeScript is Javascript + strong type. Don't try to bring in all OO implementation to it (although it's tempting sometimes).