As a first-year university student, I recently discovered that the canDeactivate()
guard in Angular is deprecated, while the canDeactivateFn
guard functions without any issues. Admittedly, navigating through official documentation is still new to me. From what I've gathered, canActivateFn
and canDeactivateFn
are now treated as functions rather than classes. You can directly incorporate the component you wish to utilize canDeactivateFn
with in the function definition. Below is an example of how I defined my canDeactivateFn
function.
/*
My intention is to automatically save data when a user navigates away from a component.
*/
export const leaveRoute: CanDeactivateFn<EnglishComponent> = (
// The EnglishComponent is the target component for modification
component: EnglishComponent,
currentRoute: ActivatedRouteSnapshot,
currentState: RouterStateSnapshot,
nextState: RouterStateSnapshot):
Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree => {
// The logic within this 'hello' block never gets executed. How can I ensure it runs when navigating away from the component?
console.log('hello')
component.formValue = component.form.value
component.form.setValue(component.formValue)
return true
}
This is how my routing is configured.
{
path: 'en',
component: EnglishComponent,
canDeactivate: [(component: EnglishComponent) => true]
},
Now, here comes my question - How do I effectively implement the canDeactivateFn
guard? What additions should be made, and what aspects should be omitted? If possible, I prefer guidance from the official Angular documentation to enhance my comprehension. However, if that's not feasible, no worries at all.
I appreciate your assistance in advance :)