I would like to implement a CanDeactivate Guard in my Ionic Angular application. I've found out, that I should use the new "CanDeactivateFn" Guard, but I can't found any information or an example how to do it. Can somebody give me an example? That would be very helpful!
Asked
Active
Viewed 356 times
0
-
1Next time maybe lookup in the official docs https://angular.io/cli/generate#guard-command. Try this -> ng g guard name --functional. If using angular cli >= 16 the flag --functional will be the default – Bruno Miguel May 26 '23 at 15:05
1 Answers
1
export const GlossaryOutGuard: CanDeactivateFn<GlossaryComponent> =
(
component: GlossaryComponent,
currentRoute: ActivatedRouteSnapshot,
currentState: RouterStateSnapshot,
nextState: RouterStateSnapshot
): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree =>
{
let sweetAlertService: SweetAlertService = inject(SweetAlertService);
if(component.viewMode == 'GLOSSARY' && component.isSomeMenuItemUnderEdition()) {
let menuItemUnderEdition: EditGlossaryItemComponent = component.getMenuItemUnderEdition()!;
return sweetAlertService
.showGlossaryDataLosingQuestion(menuItemUnderEdition.label!)
.then((result: SweetAlertResult) => result.isConfirmed);
}
return true;
}

Bruno Miguel
- 1,003
- 3
- 13
- 26