Mam komponent, który otrzymuje tablicę imageobiektów jako Inputdane.
export class ImageGalleryComponent {
@Input() images: Image[];
selectedImage: Image;
}
Chciałbym, gdy składnik ładuje selectedImagewartość ustawioną na pierwszy obiekt imagestablicy. Próbowałem to zrobić w OnInithaku cyklu życia w następujący sposób:
export class ImageGalleryComponent implements OnInit {
@Input() images: Image[];
selectedImage: Image;
ngOnInit() {
this.selectedImage = this.images[0];
}
}
to daje mi błąd, Cannot read property '0' of undefinedco oznacza, że imageswartość nie jest ustawiona na tym etapie. Próbowałem też OnChangeshaka, ale utknąłem, ponieważ nie mogę uzyskać informacji o tym, jak obserwować zmiany w tablicy. Jak mogę osiągnąć oczekiwany efekt?
Komponent nadrzędny wygląda następująco:
@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
);
}
}
Szablon komponentu nadrzędnego ma to
...
<image-gallery [images]="images"></image-gallery>
...
imagesdane są wypełniane w komponencie nadrzędnym? To znaczy, czy odbywa się to za pośrednictwem żądań http? Jeśli tak, może lepiej byłoby, gdyby składnik ImageGalleryComponent subskrybował () obserwowalny http.