Tôi có một thành phần nhận một mảng các image
đối tượng dưới dạng Input
dữ liệu.
export class ImageGalleryComponent {
@Input() images: Image[];
selectedImage: Image;
}
Tôi muốn khi thành phần tải selectedImage
giá trị được đặt thành đối tượng đầu tiên của images
mảng. Tôi đã cố gắng làm điều này trong OnInit
móc vòng đời như thế này:
export class ImageGalleryComponent implements OnInit {
@Input() images: Image[];
selectedImage: Image;
ngOnInit() {
this.selectedImage = this.images[0];
}
}
điều này mang lại cho tôi một lỗi Cannot read property '0' of undefined
có nghĩa là images
giá trị không được đặt trong giai đoạn này. Tôi cũng đã thử OnChanges
hook nhưng tôi bị mắc kẹt vì tôi không thể lấy thông tin về cách quan sát các thay đổi của một mảng. Làm thế nào tôi có thể đạt được kết quả mong đợi?
Thành phần mẹ trông giống như sau:
@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
);
}
}
Mẫu của thành phần mẹ có cái này
...
<image-gallery [images]="images"></image-gallery>
...
images
Dữ liệu được điền như thế nào trong thành phần chính? Tức là nó thông qua (các) yêu cầu http? Nếu vậy, tốt hơn hết bạn nên đăng ký ImageGalleryComponent () vào http có thể quan sát được.