我有一个组件,它接收image
对象数组作为Input
数据。
export class ImageGalleryComponent {
@Input() images: Image[];
selectedImage: Image;
}
我想在组件加载时将selectedImage
值设置为images
数组的第一个对象。我试图在OnInit
生命周期挂钩中执行以下操作:
export class ImageGalleryComponent implements OnInit {
@Input() images: Image[];
selectedImage: Image;
ngOnInit() {
this.selectedImage = this.images[0];
}
}
这给我一个错误Cannot read property '0' of undefined
,这意味着images
该阶段未设置该值。我也尝试过OnChanges
钩子,但由于无法获取有关如何观察数组变化的信息而感到困惑。如何获得预期的结果?
父组件如下所示:
@Component({
selector: 'profile-detail',
templateUrl: '...',
styleUrls: [...],
directives: [ImageGalleryComponent]
})
export class ProfileDetailComponent implements OnInit {
profile: Profile;
errorMessage: string;
images: Image[];
constructor(private profileService: ProfileService, private routeParams: RouteParams){}
ngOnInit() {
this.getProfile();
}
getProfile() {
let profileId = this.routeParams.get('id');
this.profileService.getProfile(profileId).subscribe(
profile => {
this.profile = profile;
this.images = profile.images;
for (var album of profile.albums) {
this.images = this.images.concat(album.images);
}
}, error => this.errorMessage = <any>error
);
}
}
父组件的模板具有此
...
<image-gallery [images]="images"></image-gallery>
...
images
在父组件中填充数据?即是通过http请求吗?如果是这样,最好将ImageGalleryComponent subscription()绑定到http observable。