Angular:生命周期钩子是Component可用的输入数据 [英] Angular: In which lifecycle hook is input data available to the Component
问题描述
我有一个组件,它接收一个 image
对象数组作为输入
数据。
I have a component which receives an array of image
objects as Input
data.
export class ImageGalleryComponent {
@Input() images: Image[];
selectedImage: Image;
}
我希望当组件加载 selectedImage
value设置为 images
数组的第一个对象。我试图在 OnInit
生命周期钩子中执行此操作:
I would like when the component loads the selectedImage
value be set to the first object of the images
array. I have tried to do this in the OnInit
lifecycle hook like this:
export class ImageGalleryComponent implements OnInit {
@Input() images: Image[];
selectedImage: Image;
ngOnInit() {
this.selectedImage = this.images[0];
}
}
这给了我一个错误无法读取未定义
的属性'0',这意味着此阶段未设置 images
值。我也尝试了 OnChanges
钩子,但是因为我无法获得有关如何观察阵列变化的信息而陷入困境。我怎样才能达到预期的效果?
this gives me an error Cannot read property '0' of undefined
which means the images
value isn't set on this stage. I have also tried the OnChanges
hook but I'm stuck because i can't get information on how to observe changes of an array. How can I achieve the expected result?
父组件如下所示:
@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>
...
推荐答案
填充输入属性在调用 ngOnInit()
之前。但是,这假定在创建子组件时已经填充了提供输入属性的父属性。
Input properties are populated before ngOnInit()
is called. However, this assumes the parent property that feeds the input property is already populated when the child component is created.
在您的方案中,情况并非如此–图像数据正在从服务异步填充(因此是http请求)。因此,当调用 ngOnInit()
时,不会填充输入属性。
In your scenario, this is not the case – the images data is being populated asynchronously from a service (hence an http request). Therefore, the input property will not be populated when ngOnInit()
is called.
要解决您的问题,从服务器返回数据时,请将新数组分配给父属性。在孩子中实施 ngOnChanges()
。当角度变化检测将新数组值传播给子节点时,将调用 ngOnChanges()
。
To solve your problem, when the data is returned from the server, assign a new array to the parent property. Implement ngOnChanges()
in the child. ngOnChanges()
will be called when Angular change detection propagates the new array value down to the child.
这篇关于Angular:生命周期钩子是Component可用的输入数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!