2016-08-22 34 views
0

我已經從演示數據存儲在in-memory-data-service.ts的角色團隊克隆了tour of heroes tutorial product。由於我的首選後端是django-rest-framework,因此我需要將它們鏈接在一起。如何顯示從Django-rest-framework中檢索到的json的數據?

例如,我的英雄們正在翻譯本地主機:8000/api/v1/heroes /。

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

我應該怎麼做,除了消除in-memory-data-service.ts更換英雄榜通過JSON Django在後端提供?如果你會告訴我我是否需要模型聲明

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

但是如果rest-framework給了我完整的存儲在JSON中的對象結構。

回答

1

要消耗任何REST API,你必須寫一個服務像下面,

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()) 
    } 
} 

希望這有助於!

相關問題