0
0
Angularframework~10 mins

Route guards (canActivate, canDeactivate) in Angular - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to implement a canActivate guard that allows navigation only if the user is logged in.

Angular
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
  return this.authService.[1]();
}
Drag options to blanks, or click blank then click option'
AisLoggedIn
BcheckUser
CcanActivate
DallowAccess
Attempts:
3 left
💡 Hint
Common Mistakes
Using a method that does not return a boolean
Calling a method that does not exist in authService
2fill in blank
medium

Complete the code to implement a canDeactivate guard that asks the user for confirmation before leaving the page.

Angular
canDeactivate(component: any, currentRoute: ActivatedRouteSnapshot, currentState: RouterStateSnapshot, nextState?: RouterStateSnapshot): boolean {
  return window.[1]('Do you really want to leave?');
}
Drag options to blanks, or click blank then click option'
Aprompt
BconfirmLeave
Calert
Dconfirm
Attempts:
3 left
💡 Hint
Common Mistakes
Using alert which does not return a value
Using prompt which returns a string, not a boolean
3fill in blank
hard

Fix the error in the canActivate guard method to properly return an Observable<boolean>.

Angular
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
  return this.authService.isLoggedIn()[1](map(loggedIn => loggedIn));
}
Drag options to blanks, or click blank then click option'
A.map
B.subscribe
C.pipe
D.then
Attempts:
3 left
💡 Hint
Common Mistakes
Using subscribe which returns a Subscription, not an Observable
Using then which is for Promises, not Observables
4fill in blank
hard

Fill both blanks to create a canDeactivate guard that calls a component method to check if it can deactivate.

Angular
canDeactivate(component: [1], currentRoute: ActivatedRouteSnapshot, currentState: RouterStateSnapshot, nextState?: RouterStateSnapshot): boolean {
  return component.[2]();
}
Drag options to blanks, or click blank then click option'
ACanComponentDeactivate
BcanDeactivate
CcanLeave
DconfirmExit
Attempts:
3 left
💡 Hint
Common Mistakes
Using a component type that does not define canDeactivate
Calling a method name that does not exist on the component
5fill in blank
hard

Fill all three blanks to create a route configuration that uses both canActivate and canDeactivate guards.

Angular
const routes: Routes = [
  {
    path: 'edit',
    component: EditComponent,
    canActivate: [[1]],
    canDeactivate: [[2]],
    data: { title: '[3]' }
  }
];
Drag options to blanks, or click blank then click option'
AAuthGuard
BUnsavedChangesGuard
CEdit Page
DLoginGuard
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up canActivate and canDeactivate guards
Using guard names that do not exist in the project