accountsroute that only users that are logged in can navigate to. This page also has forms and we want to make sure the user has submitted unsaved changes before leaving the accounts page.
LoginRouteGuardwill be checked by the router when activating the
SaveFormsGuardwill be checked when leaving that route.
CanActivateinterface by implementing the
canActivatereturns true, the user can activate the route. When
canActivatereturns false, the user cannot access the route. In the above example, we allow access when the user is logged in.
canActivatecan also be used to notify the user that they can't access that part of the application, or redirect them to the login page.
CanDeactivateworks in a similar way to
CanActivate, but there are some important differences. The
canDeactivatefunction passes the component being deactivated as an argument to the function:
canDeactivatefunctions can return values of type
Observable<boolean>(an Observable that resolves to
boolean). If you need to do an asynchronous request (like a server request) to determine whether the user can navigate to or away from the route, you can simply return an
Observable<boolean>. The router will wait until it is resolved and use that value to determine access.
Observable<boolean>which resolves to true if the user clicks 'OK', or false if user clicks 'Cancel'.
canDeactivatefunctions can also return values of type
Observable<UrlTree>(an Observable that resolves to
UrlTreeis a data structure that represents a parsed URL. If a route guard returns a
UrlTree, the current navigation is cancelled and replaced with a new navigation to the Url specified in the