对象中的嵌套对象数组 - Angular 2

Nested object array in objects - Angular 2

我正在使用 Angular 2 和 JSONP 从 api 中获取值。 api 正在返回一个对象(嵌套对象)。下面是我正在尝试使用的代码。

数据

{  
 "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 模板

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

在 HTML 模板中,我尝试使用 Elvis 运算符,但没有返回任何值。控制台日志将正确的数据显示为一个单独的对象。 如何获取不同流派的id和名称?

{{movies?.genres?.id}} 

无法正常工作,即使在提供索引后也是如此。

它正在使用索引的知识!看看我的 plunker 作为演示:https://plnkr.co/edit/vI9azM3JkytZ51SifNUa?p=preview

但索引必须存在,因此请先使用 *ngIf 检查它或使用 *ngFor 遍历所有可能的项目。

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 {}