[英]Should I call ngOnInit() again in Angular?
I am new to Angular and the question may sound stupid. 我是Angular的新手,这个问题可能听起来很愚蠢。 Please bear with me.
请多多包涵。
I have defined my ngOnInit
like: 我已经定义了我的
ngOnInit
如:
ngOnInit() {
this.rowData = this.studentService.getStudents();//Make http calls to populate data
}
And in an event I call ngOnInit again as I need to reload the data: 在一个事件中,我再次调用ngOnInit,因为我需要重新加载数据:
onSomeEvent(){
this.ngOnInit();
}
Is this OKAY? 这个可以吗? Or I should write the line to call http again if
ngOnInit()
is a costly method. 或者如果
ngOnInit()
是一种代价高昂的方法,我应该再写一行来再次调用http。
No, this is not a good practice. 不,这不是一个好习惯。
Better is to call some method from ngOnInit
and reCall the same method when needed. 更好的方法是从
ngOnInit
调用一些方法,并在需要时重新调用相同的方法。 Like this- 像这样-
ngOnInit() {
this.onLoad();
}
onLoad() {
this.rowData = this.studentService.getStudents();//Make http calls to populate data
}
onSomeEvent(){
this.onLoad();
}
The better way to do it : 更好的方法:
ngOnInit(){
this.loadData();
}
//load data
loadData(){
this.rowData = this.studentService.getStudents();
}
//on change event
ngOnChanges(){
this.loadData()
}
//capture data on other event
otherEvent(){
this.loadData()
}
ngOnInit
is lifecycle hook that is called after data-bound properties of a directive are initialized so first time it call by angualr it self , so recalling this method will case alot of confusing to other and sign to poor code , so it better to break the code insde ngOnInit and called againg if need it. ngOnInit
是在指令的数据绑定属性被初始化之后调用的生命周期钩子,因此第一次由angualr调用它自己,所以回想一下这种方法会让其他人感到困惑并签署不良代码,所以最好打破代码insn ngOnInit并在需要时调用againg。
ngOnInit() {
this.refrechItems();
}
public refrechItems(): void {
// magic things
}
you may cosider samething for all other lifecycle hooks 你可以为所有其他生命周期钩子做同样的事情
Please do not do that! 请不要这样做! Angular has many different Lifecycle hooks
Angular有许多不同的Lifecycle钩子
https://angular.io/guide/lifecycle-hooks https://angular.io/guide/lifecycle-hooks
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.