I need to call a backend API inside onDestroy in Angular. I need to save the state of something if the user leave the page, so I was thinking to do that call onDestroy lifecycle, but it's not working on production.
I tried with canDeactivat on the route as well, but it's not working:
This is the routing:
{
path: "",
component: CardBuilderStepperComponent,
pathMatch: "prefix",
canDeactivate: [(component: CardBuilderStepperComponent) => component.canDeactivate()],
...
and this is the method:
canDeactivate(): Promise<boolean> | boolean {
return new Promise<boolean>((resolve) => {
this.router.events
.pipe(
filter((event) => event instanceof NavigationEnd),
take(1)
)
.subscribe((event) => {
const urlAfterRedirects = (event as NavigationEnd).urlAfterRedirects;
if (urlAfterRedirects === "/") this.navigationService.updateSnapshotNoChangeLocation();
resolve(true);
});
});
}
ngOnDestroy(): void {
this.store.dispatch(LayoutActions.closeExpanseBar());
console.log("destroy");
}
It's not working like that, but it works if resolve(true) goes outside the subscription. But I need that resolve(true) and I need to destroy the component only when the backend API is done. If I leave it outside the subscription, the component gets destroyed before the API backend get called.
Any idea on how can I solve that?