0

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.

1 Answer 1

1

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 {}
Sign up to request clarification or add additional context in comments.

1 Comment

Well, thanks. I was able to solve it based on console output and hint from your answer. The object name was different thn what I was using.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.