Complete the code to implement a canActivate guard that allows navigation only if the user is logged in.
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
return this.authService.[1]();
}The isLoggedIn method checks if the user is logged in and returns a boolean. This is the correct method to use in a canActivate guard.
Complete the code to implement a canDeactivate guard that asks the user for confirmation before leaving the page.
canDeactivate(component: any, currentRoute: ActivatedRouteSnapshot, currentState: RouterStateSnapshot, nextState?: RouterStateSnapshot): boolean {
return window.[1]('Do you really want to leave?');
}The window.confirm method shows a dialog box with OK and Cancel buttons and returns true if OK is clicked. This is suitable for canDeactivate guards.
Fix the error in the canActivate guard method to properly return an Observable<boolean>.
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
return this.authService.isLoggedIn()[1](map(loggedIn => loggedIn));
}In Angular with RxJS, pipe is used to chain operators on Observables. Using pipe with a map operator is the correct way to transform the Observable.
Fill both blanks to create a canDeactivate guard that calls a component method to check if it can deactivate.
canDeactivate(component: [1], currentRoute: ActivatedRouteSnapshot, currentState: RouterStateSnapshot, nextState?: RouterStateSnapshot): boolean { return component.[2](); }
The guard expects the component to implement CanComponentDeactivate interface and call its canDeactivate method to decide if navigation is allowed.
Fill all three blanks to create a route configuration that uses both canActivate and canDeactivate guards.
const routes: Routes = [
{
path: 'edit',
component: EditComponent,
canActivate: [[1]],
canDeactivate: [[2]],
data: { title: '[3]' }
}
];The AuthGuard protects the route from unauthorized access (canActivate). The UnsavedChangesGuard prevents leaving the page with unsaved changes (canDeactivate). The data title is set to 'Edit Page' for display purposes.