I am fairly new to angular 2, and trying to learn more about it.
My question here is: How do we refresh a component (re-invoke ngOnInit).
This component will be calling an API to retrieve some data from a database. and if a button is clicked, a PUT request will be sent to an API to update the data in the database. Since the change happens in the database instead of the component itself, I dont think ngOnChange or other change checking method will work. Here I am trying to let the ngOnInit be invoked again so the component can receive updated data.
I have tried router nagivate to refresh this page, but it does not work.
All the HTTP method happens in the another service file, I will not display them here since it's not relevant.
app.module.ts
@NgModule({
imports: [
RouterModule.forRoot([{path: 'data', component: DataComponent}]);
]
})
data.component.ts
@Component({
template: `
<button (click)= "onclick()">Click Me</button>
`,
....
});
export class DataComponent implements OnInit{
fetchData(): void{
this.dataService.dataSessions().subscribe(
data => this.data= data,
error=> console.error(error),
()=> {}
);
}
onclick(){
this.dataChangeService.updateData().subscribe( response=> console.log(response));
this.router.navigate['/data'];
}
ngOnInit(): void{
this.fetchData();
}
Any answer will be appreciated, I am always happy to learn more.
Try to call the this.fetchData() method once your call to the backend is resolved. Something like:
response=> { this.fetchData() ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With