user2929318 user2929318 - 2 months ago 23
HTTP Question

Nested object array in objects - Angular 2

I'm using Angular 2 and JSONP to get the value from the api. The api is returning an Object (Nested Objects). Below is the code which I'm trying to use.

Data

{
"adult":false,
"backdrop_path":"/eIOTsGg9FCVrBc4r2nXaV61JF4F.jpg",
"belongs_to_collection":null,
"budget":175000000,
"genres":[
{
"id":12,
"name":"Adventure"
},
{
"id":18,
"name":"Drama"
},
{
"id":14,
"name":"Fantasy"
}
],
"poster_path":"/vOipe2myi26UDwP978hsYOrnUWC.jpg",
}


Service.ts

fetchData(){
return this.jsonp.get('https://api.themoviedb.org/3/movie/278927?api_key=fd35dcdcfbba840ef2f9ea42c5c55869&callback=JSONP_CALLBACK').map(
(res) => res.json()
);
}


component.ts

export class MovieComponent implements OnInit {

movies = Object;
constructor(private dataService: DataService) { }

ngOnInit() {
this.dataService.fetchData().subscribe(
(data) => this.movies = data
);
}
}


HTML Template

{{movies.budget}} //This is working
{{movies.genres[0].id}} //This is not working


In the HTML Template, I've tried using Elvis Operator, but that is not returning any value. The console log is showing proper data as one single object. How to get the id and name of different genres?

{{movies?.genres?.id}}


is not working, even after providing an index with it.

Answer

It is working with the knowledge of the index! See my plunker as a demo: https://plnkr.co/edit/vI9azM3JkytZ51SifNUa?p=preview

But the index has to be there, so check it first with *ngIf or use *ngFor to iterate through all possible items.

import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2 *ngIf="names && names.length">Hello {{names[0]}}</h2>

      <h2 *ngFor="let n of names">Hi {{n}}</h2>
    </div>
  `,
})
export class App {
  constructor() {
    this.names = [];

    setTimeout(() => this.names = ['Angular2', 'Name2', 'name3'], 3000);
  }
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}