Search code examples
javascriptangulartypescriptangular15

Injecting the Router and the ActivatedRouteSnapshot into an Angular 15 router guard?


I'm trying to convert a pre Angular 15 Router Guard to a Router Guard Function.

The current version looks like this:

@Injectable({
  providedIn: 'root'
})
export class TopicGuardService implements CanActivate {

  constructor(private router: Router) { }
  canActivate(route: ActivatedRouteSnapshot): boolean {
    const topicStore: EStore<Topic> = route.data[TOPIC_STORE_KEY]
    const id = route.paramMap.get("topic")
    const topic = topicStore.findOneByID(id || '')
    if (topic) {
      return true
    }
    this.router.navigate(['/404'])
    return false
  }
}

It injects the Router and gets the route via the canActivate method.

To convert this to the functional version can we just do something like this:

export function topicGuard(router: Router, route: ActivatedRouteSnapshot) { ... }

Is that the correct way to inject the dependencies into the function?


Solution

  • I believe you can use inject()

    import {inject} from '@angular/core';
    import {Router} from '@angular/router';
    import {tap} from 'rxjs';
    import {SomeOtherService} from '../some-other-service.service';
    
    export const myGuard= () => {
        const router = inject(Router);
        const service = inject(SomeOtherService)
        return service.isAllowed().pipe(
        tap((allowed) => {
          if(allowed){
             return true;
          } else {
            router.navigate(['/nope'])
          }
        }
      ))
    }