liveBook · Manning

canActivate method

As explained in Modern Angular

canActivate is an Angular guard method that returns a route-activation decision or a redirect tree.

canActivate is the route-guard entry point that decides whether navigation may continue or returns an UrlTree redirect. Older Angular guards implement it on a state-free class; the modern approach defines a CanActivateFn and uses inject directly, removing the class when dependency injection is the only reason it exists. section 3.3.1

Protecting an employees route

A functional authGuard injects AuthService and Router, maps isAuth$ to either true or router.createUrlTree(['/login']), and is registered with canActivate: [authGuard]. This restricts HRMS business pages to authenticated users while redirecting others. section 3.3.1

Listing 3.9 Functional route guard
import { inject } from '@angular/core';
import { CanActivateFn, Router, } from '@angular/router';
import { map } from 'rxjs/operators';
import { AuthService } from 'src/app/services/auth.service';

export const authGuard: CanActivateFn = () => {  #1
    const router = inject(Router);  #2
    const authService = inject(AuthService);

    return authService.isAuth$.pipe(  #3
        map((isAuth) => isAuth || router.createUrlTree(['/login'])),  #4
    );
}

Shows the functional CanActivateFn implementation, dependency injection, observable decision, and login redirect. section 3.3.1

For incremental migration:

  • Register an existing class-based guard with mapToCanActivate([AuthGuard]) while converting guards individually. section 3.3.4
  • Replace the class with a CanActivateFn when its main purpose is dependency injection and a single canActivate decision. section 3.3.1

How Modern Angular covers it

How deep it goes
Contrasts a state-free class method with a functional CanActivateFn, including injection, observable mapping, redirects, and registration.
Examples
Uses an HRMS employees route, AuthService.isAuth$, a /login UrlTree, and class-to-function migration.
What it assumes
Assumes familiarity with Angular routing, dependency injection, services, and RxJS observables.
What you can do after
Apply it via Angular routing to allow authenticated users through and redirect unauthenticated users to /login.
How it connects
Connects route guards with dependency injection, authentication services, Router, UrlTree, observables, and functional routing.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern Angular. The section links point to the parts of the book it draws on.