मेरे पास एक घटक है जो डेटा के 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 अनुरोध (एस) के माध्यम से है? यदि ऐसा है, तो आप http ऑब्जेक्टिव के लिए ImageGalleryComponent सब्सक्रिप्शन () कर सकते हैं।