Veri imageolarak nesneler dizisini alan bir bileşenim var Input.
export class ImageGalleryComponent {
@Input() images: Image[];
selectedImage: Image;
}
Bileşen yüklendiğinde selectedImagedeğerin imagesdizinin ilk nesnesine ayarlanmasını isterim . Bunu OnInityaşam döngüsü kancasında şu şekilde yapmaya çalıştım :
export class ImageGalleryComponent implements OnInit {
@Input() images: Image[];
selectedImage: Image;
ngOnInit() {
this.selectedImage = this.images[0];
}
}
bu bana bir hata veriyor , bu Cannot read property '0' of undefinedda imagesdeğerin bu aşamada ayarlanmadığı anlamına geliyor . OnChangesKancayı da denedim ama takılı kaldım çünkü bir dizideki değişiklikleri nasıl gözlemleyeceğime dair bilgi alamıyorum. Beklenen sonuca nasıl ulaşabilirim?
Ana bileşen şuna benzer:
@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
);
}
}
Üst bileşenin şablonunda buna sahiptir
...
<image-gallery [images]="images"></image-gallery>
...
imagesVeriler üst bileşende nasıl doldurulur? Yani, bir http istek (leri) aracılığıyla mı? Öyleyse, ImageGalleryComponent'in http gözlemlenebilir'e abone olması () daha iyi olabilir.