Reputation: 453
I have a scenario where i have to send data to api (database) before specific component is destroyed. As its described in angular2 life cycle, one method is executed before component is destroyed and its called ngOnDestroy
. But as specified in documentation, that is an void function so it does not wait for some results to return.
My quesiton is how can i perform my call to api in ngOnDestroy function and wait while it completes?
If i just call update function it works, but when i route from one component to another, the data from first component are not yet updated while next component loads old data (if i hit refresh then i get new data). So problem is that i cannot wait for update function to execute fully and then allow component destruction and routing to next component which will load correct, updated data:
updateData(data: any, callback?: Function) {
this.apiService.update(data).then(response => {
callback(response);
}
}
ngOnDestroy() {
this.updateData(this.data);
}
// Maybe i could somehow use callback functionality to postpone execution of ngOnDestroy function
ngOnDestroy() {
this.updateData(this.data, response => {
});
}
Or is there any other way to solve this situation?
Upvotes: 4
Views: 4711
Reputation: 19622
Instead of doing something like this try this approach much cleaner and better i guess.
Make use of a Shared service, pass on the r values to the shared service on Destroy
and then when navigating to the second component. have a Router resolve that will make sure data is populated and kept at your disposal when the component is loaded.
For shared services check this LINK- question 2 and for Router resolve LINK.
You may also reach out for redux or ngrx areif you want better readability LINK
Upvotes: 4