Angular2 Mapping nested json array to model Angular2 Mapping nested json array to model angular angular

Angular2 Mapping nested json array to model


You can simplify your model and your mapping a lot.You don't need to map your API response manually. JavaScript/TypeScript can do this for you.

First you need multiple interfaces.

export interface DeiInstance {     base_url: string;    date: string;    lname: string;    name: string;    description: string;    id: number;    creationDate: string; //probably date    version: string    metrics: Metric[];    key: string; } export interface Metric {      val: decimal;      frmt_val: decimal;      key: string; }

You can then use the as-"operator" of TypeScript to cast your API response to the DeiInstance Type.

 sealSearch(term: string): Observable<DeiInstance[]> {      return this.http.get(this.sealUrl + term)           .map(response => response.json() as DeiInstance[])           .catch(this.handleError); }

If you use interfaces instead of classes you have also the advantage that you have less production code which will be sended to the client browser.The interface is only there for pre-compile-time or however you want to call it.

Hope my code works and it solves your problem.