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 Inputdữ liệu.
export class ImageGalleryComponent {
@Input() images: Image[];
selectedImage: Image;
}
Tôi muốn khi thành phần tải selectedImagegiá trị được đặt thành đối tượng đầu tiên của imagesmảng. Tôi đã cố gắng làm điều này trong OnInitmó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 undefinedcó nghĩa là imagesgiá trị không được đặt trong giai đoạn này. Tôi cũng đã thử OnChangeshook 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>
...
imagesDữ 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.