Join the Stack Overflow Community
Stack Overflow is a community of 6.7 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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.

share|improve this question
up vote 1 down vote accepted

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 {}
share|improve this answer
    
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. – Riya Sep 18 '16 at 7:59

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.