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

时间:2016-09-16 23:34:17

标签: angularjs http angular jsonp

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

数据

{  
 "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 Operator,但这并没有返回任何值。控制台日志将正确的数据显示为单个对象。 如何获取不同类型的ID和名称?

{{movies?.genres?.id}} 

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

1 个答案:

答案 0 :(得分:1)

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

但索引必须存在,因此请先使用NSString * state = @"Unknown"; UIApplication *application = [UIApplication sharedApplication]; if ( application.applicationState == UIApplicationStateInactive ) { //The application received the notification from an inactive state, i.e. the user tapped the "View" button for the alert. //If the visible view controller in your view controller stack isn't the one you need then show the right one. state = @"UIApplicationStateInactive"; } if(application.applicationState == UIApplicationStateActive ) { //The application received a notification in the active state, so you can display an alert view or do something appropriate. state = @"UIApplicationStateActive"; } if(application.applicationState == UIApplicationStateBackground ) { state = @"UIApplicationStateBackground"; } 进行检查,或使用*ngIf迭代所有可能的项目。

*ngFor