Tuhin
Tuhin

Reputation: 43

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'. It was working with the tutorial's in-memory data, but fails when I use my django rest API.

hero.ts

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

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

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

Upvotes: 0

Views: 843

Answers (3)

Tuhin
Tuhin

Reputation: 43

I'm sorry. My while I could see the XHR response sent by my django API, there was CORS problem. I did not have to change my code. Just had to allow CORS in django. Sorry to take up your time. Thank you for your suggestions.

Upvotes: 0

baumgarb
baumgarb

Reputation: 2197

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[]

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

Option 2 (preferable): Create a model (e.g. HeroResult) that represents what your server actually returns to have full type safety

export class HeroResult {
    heroes: Hero[];
}

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

Upvotes: 0

Compiler v2
Compiler v2

Reputation: 3595

You can use within your component 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.

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/

Others

Map Json to object in angular

https://coursetro.com/posts/code/171/Angular-7-Tutorial---Learn-Angular-7-by-Example (scroll down to the HTTP service part of it)

Upvotes: 1

Related Questions