amazingbasil amazingbasil - 3 months ago 16
reST (reStructuredText) Question

How to display data from json retrieved from django-rest-framework?

I've cloned tour of heroes tutorial product from angular team where demo data is storing in

in-memory-data-service.ts
. Since my preferred backend is django-rest-framework, I need to link them together.

For example, my heroes are translating from localhost:8000/api/v1/heroes/.

[
{
"name": "Greg",
"id": 5,
},
{
"name": "Krek",
"id": 6,
}
]


What should I do except removing
in-memory-data-service.ts
to replace heroes list with provided by django backend via json? It would be great if you'll tell me do I need model declaration

export class Hero {
id: number;
name: string;
}


yet if rest-framework gives me full objects structure stored in JSON.

Answer

To consume any REST API you have to write a service like below,

 import { Injectable } from 'angular2/core';
 import { Http, Response } from 'angular2/http';
 import { Observable } from 'rxjs/Rx';

 export class Hero {
    id: number;
    name: string;
 }

 @Injectable()
 export class HeroService {
   constructor(private _http: Http) { }

   getHeroes() {
     return this._http.get('api/v1/heroes')
      .map((response: Response) => <Hero []>response.json())
   }
}

Hope this helps!!

Comments