I am trying to implement canDeactivate guard for unsaved edit. And when I am testing, it seems that route history is getting broken. I know solution is there in angular but it is post v 12 and currently I am working on a project in angular 8. And I am not able to find solution for the same.
Here is my code :
guard :
import { CanDeactivate } from '@angular/router';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
export interface ComponentCanDeactivate {
canDeactivate: () => boolean | Observable<boolean>;
}
@Injectable()
export class PendingChangesGuard implements CanDeactivate<ComponentCanDeactivate> {
canDeactivate(component: ComponentCanDeactivate): boolean | Observable<boolean> {
return component.canDeactivate() ?
true :
confirm('WARNING: You have unsaved changes. Press Cancel to go back and save these changes, or OK to lose these changes.');
}
}
Component :
@HostListener('window:beforeunload')
canDeactivate(): Observable<boolean> | boolean {
return !this.isDataUpdated();
}
routing :
const routes: Routes = [{ path: '', component: ListViewTableComponent, pathMatch: 'full',canDeactivate:[PendingChangesGuard] }];
Please guide me where I am doing wrong.