【问题标题】:How to display data from json retrieved from django-rest-framework?如何显示从 django-rest-framework 检索到的 json 数据?
【发布时间】:2016-12-29 10:27:21
【问题描述】:

我从 Angular 团队克隆了 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 后端通过json 提供的英雄列表替换英雄列表之外,我应该怎么做?如果你能告诉我我需要模型声明,那就太好了

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

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

【问题讨论】:

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


    【解决方案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())
       }
    }
    

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 2018-07-17
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 2019-08-13
      • 1970-01-01
      • 1970-01-01
      • 2018-07-24
      • 1970-01-01
      相关资源
      最近更新 更多