Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I call ngOnInit() again in Angular?

I am new to Angular and the question may sound stupid. Please bear with me.

I have defined my ngOnInit like:

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:

onSomeEvent(){
 this.ngOnInit();
}

Is this OKAY? Or I should write the line to call http again if ngOnInit() is a costly method.

like image 667
vibhor1997a Avatar asked Dec 07 '22 14:12

vibhor1997a


2 Answers

No, this is not a good practice.

Better is to call some method from ngOnInit and reCall the same method when needed. Like this-

ngOnInit() {
 this.onLoad();
}

onLoad() {
this.rowData = this.studentService.getStudents();//Make http calls to populate data
}

onSomeEvent(){
 this.onLoad();
}
like image 154
Pardeep Jain Avatar answered Jan 11 '23 09:01

Pardeep Jain


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()
}
like image 27
Akj Avatar answered Jan 11 '23 08:01

Akj