How to implement CanDeactivateFn in Angular15

127 views Asked by At

I would like to implement a CanDeactivate Guard in my 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 someone help me to implement this logic.

recently we did update to angular 15, we noticed few functionalities are not working as excepted(especailly whenever calling router.navigate) we notice candecativate methode was depreceted in angular 15 and they are suggesting to use inject method and candecativefn. when i try to implement was facing so many issues.

the below is the old candeactivateegurad.ts file

export interface CanComponentDeactivate {
    canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}

export class CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate>
{
  currentSate: string;

  canDeactivate(
    component: CanComponentDeactivate,
    currentRoute: ActivatedRouteSnapshot,
    currentState: RouterStateSnapshot,
    nextState?: RouterStateSnapshot
  ) {
       
    if (
      this.currentUrl === currentState.url &&
      this.currentUrl !== '/datm/0'
    ) {
            return true;
        }
        if (component === null) {
            return true;
        }
    const isCanDeactivate = component.canDeactivate
      ? component.canDeactivate()
      : true;
        if (isCanDeactivate) {
            this.currentUrl = currentState.url;
        }
        return isCanDeactivate;
    }
}

in component routes we called this guard, routing.ts file

{
        path: PathNames.exampleComponent,
        component: exampleComponent,
        canDeactivate: [CanDeactivateGuard],
   
    }

component.ts

in other components we called this guards as refrences to change the currentUrl value like below

constructor(private canDeactivateGuard: CanDeactivateGuard,)
  if(value){
  this.canDeactivateGuard.currentUrl = '';
}
0

There are 0 answers