如何显示从django-rest-framework检索到的json数据?

时间:2016-08-22 18:56:34

标签: json django rest angular django-rest-framework

我已从角色小组克隆tour of heroes tutorial product,其中演示数据存储在in-memory-data-service.ts中。由于我首选的后端是django-rest-framework,我需要将它们链接在一起。

例如,我的英雄正在从localhost翻译:8000 / api / v1 / heroes /.

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

除了删除in-memory-data-service.ts以替换django backend通过json提供的英雄列表外,我该怎么办?如果您告诉我,我需要模型声明

,那将是很棒的
export class Hero {
  id: number;
  name: string;
}

但是,如果rest-framework为我提供了存储在JSON中的完整对象结构。

1 个答案:

答案 0 :(得分: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())
   }
}

希望这会有所帮助!!

相关问题