简体   繁体   English

如何将JSON响应转换为服务中的角度对象数组?

[英]How to convert JSON response to array of angular objects within service?

EDIT: no need to answer, the problem was elsewhere. 编辑:无需回答,问题出在其他地方。 I apologize :( 我道歉 :(

I need getHeroes() to return an array of 'Hero'. 我需要getHeroes()返回一个数组'Hero'。 It was working with the tutorial's in-memory data, but fails when I use my django rest API. 它正在使用教程的内存中数据,但是当我使用django rest API时失败。

hero.ts hero.ts

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

hero.service.ts hero.service.ts

getHeroes (): Observable<Hero[]> {
      return this.http.get<Hero[]>(this.heroesUrl).pipe(
      map(response => response['heroes']),
      tap(_ => this.log('fetched heroes')),
      catchError(this.handleError<Hero[]>('getHeroes', []))
    );
}

JSON response from API 来自API的JSON响应

{
  "heroes": [
    {
      "id": 1,
      "name": "hero1"
    },
    {
      "id": 2,
      "name": "hero2"
    }
  ]
}

You can use within your component subscribe : 您可以在组件内部使用subscribe

import { Hero } from "./heroComponent";

export class SomeComponent implements OnInit {

  heroes: Hero;

  constructor(private serv: YourService) { }

  ngOnInit() {
    this.serv.getHeroes().subscribe(serv => {
        this.heroes = serv
        console.log(this.heroes);
    });
  }

}

Of course, change some stuff to make it fit your code. 当然,请更改一些内容以使其适合您的代码。 It should map your JSON to to the Object. 它应该将您的JSON映射到Object。

See if any of these help as well: 查看以下任何帮助:

This might be more to what you are asking: https://nehalist.io/working-with-models-in-angular/ 这可能符合您的要求: https : //nehalist.io/working-with-models-in-angular/

Others 其他

Map Json to object in angular 将Json映射到角度对象

https://coursetro.com/posts/code/171/Angular-7-Tutorial---Learn-Angular-7-by-Example (scroll down to the HTTP service part of it) https://coursetro.com/posts/code/171/Angular-7-Tutorial---Learn-Angular-7-by-Example (向下滚动至其中的HTTP服务部分)

There's two options for this (leaving out error handling for brevity here): 有两个选项(此处为简洁起见,省略了错误处理):

Option 1: Treat the result as an any and cast the heroes property to an Hero[] 选项1:将结果视为any ,并将heroes属性投射给Hero[]

getHeroes(): Observable<Hero[]> {
    return this.http.get<any>(this.heroesUrl).pipe(
        map(res => res.heroes as Hero[])
    );
}

Option 2 (preferable): Create a model (eg HeroResult ) that represents what your server actually returns to have full type safety 选项2(首选):创建一个模型(例如HeroResult ),该模型表示服务器实际返回的具有完全类型安全性的模型

export class HeroResult {
    heroes: Hero[];
}

getHeroes(): Observable<Hero[]> {
    return this.http.get<HeroResult>(this.heroesUrl).pipe(
        map(res => res.heroes)
    );
}

I'm sorry. 对不起。 My while I could see the XHR response sent by my django API, there was CORS problem. 当我看到django API发送的XHR响应时,出现了CORS问题。 I did not have to change my code. 我不必更改代码。 Just had to allow CORS in django. 只是不得不允许在哥伦比亚的CORS。 Sorry to take up your time. 很抱歉占用您的时间。 Thank you for your suggestions. 谢谢你的建议。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM