Bird
0
0

Identify the error in this canActivate guard implementation:

medium📝 Debug Q14 of 15
Angular - Routing
Identify the error in this canActivate guard implementation:
export class AuthGuard implements CanActivate {
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    if (this.authService.isLoggedIn()) {
      return true;
    }
  }
}
AMissing return statement when user is not logged in.
BIncorrect method name; should be canDeactivate.
CThe guard should return a Promise, not boolean.
DThe guard must not use services inside canActivate.
Step-by-Step Solution
Solution:
  1. Step 1: Check all code paths return a value

    If isLoggedIn() is false, the method returns nothing (undefined), which is invalid.
  2. Step 2: Understand guard return requirements

    canActivate must return true, false, or an observable/promise resolving to those. Missing return causes errors.
  3. Final Answer:

    Missing return statement when user is not logged in. -> Option A
  4. Quick Check:

    All canActivate paths must return true/false [OK]
Quick Trick: Always return true or false in all canActivate paths [OK]
Common Mistakes:
MISTAKES
  • Not returning false or redirect when unauthorized
  • Confusing canActivate with canDeactivate method names
  • Thinking services can't be used in guards

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes