【发布时间】:2016-10-27 12:27:33
【问题描述】:
我有一个组件接收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 请求吗?如果是这样,最好让 ImageGalleryComponent subscribe() 到 http observable。 -
@MarkRajcok
images只是像{profile: {firstName: "abc", lastName: "xyz", images: [ ... ]}}这样的父级使用的数据的一部分,这意味着如果我在子级中订阅,我仍然必须订阅父级并且我想避免重复 -
如果创建子组件时填充父组件中的图像数组,则应在调用 ngOnInit() 之前填充图像输入属性。您需要提供有关如何在父组件中填充图像数组的更多信息,以便任何人进一步帮助您(或创建一个显示问题的最小 Plunker)。
-
@MarkRajcok 我已经添加了父组件以及如何在其中填充图像。
-
所以是的,看起来您的父组件正在使用 http(因为它正在使用服务)来填充其 images 属性。由于这是一个异步操作,因此在调用其 ngOnInit() 方法时不会填充子组件的 input 属性。将您的代码从 ngOnInit() 移动到 ngOnChanges(),它应该可以工作。
标签: javascript angular typescript