2016-08-22 33 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()) 
    } 
} 

希望这有助于!

相关问题