vibhor1997a
vibhor1997a

Reputation: 2376

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.

Upvotes: 4

Views: 11272

Answers (4)

Robert Leeuwerink
Robert Leeuwerink

Reputation: 489

Please do not do that! Angular has many different Lifecycle hooks

https://angular.io/guide/lifecycle-hooks

Upvotes: 0

Muhammed Albarmavi
Muhammed Albarmavi

Reputation: 24462

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() {
 this.refrechItems();
}

public refrechItems(): void {
  // magic things
} 

you may cosider samething for all other lifecycle hooks

Upvotes: 1

Akj
Akj

Reputation: 7231

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()
}

Upvotes: 2

Pardeep Jain
Pardeep Jain

Reputation: 86800

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();
}

Upvotes: 11

Related Questions