In Angular 2+, you can protect routes with guards. The most likely used guard types are CanActivate and CanDeactivate. The first guard type decides if a route can be activated, and the second one decides if a route can be deactivated. In this section, we will discuss CanDeactivate. This is an interface having only one method canDeactivate:
export interface CanDeactivate<T> {
canDeactivate(component: T, route: ActivatedRouteSnapshot,
state: RouterStateSnapshot):
Observable<boolean> | Promise<boolean> | boolean;
}
This method can return Observable<boolean>, Promise<boolean>, or boolean. If the value of boolean is true, the user can navigate away from the route. If the value of boolean is false, the user will stay on the same view. If you want to protect your route from navigating away under some circumstances, you have to do three steps:
- Create a class that implements the CanDeactivate...