1

I everybody, I'm trying to implement auth guard on angular route but get injectable error

authentication.service.ts:

import { Injectable } from '@angular/core';
import { Router, ActivatedRoute, ParamMap, CanActivate, UrlTree, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs';

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

  public logedin: boolean = false;
  public roles: string[] = [];

  constructor() {}

  canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    console.log('canActivate service method');

    return true;
    //return false;
  }
}

app.module.ts:

imports: [
  ...
  RouterModule.forRoot([]),
  AppRoutingModule,
  ...
],

app.routing.modeule.ts:

import { AuthenticationService } from './services/authentication.service';
...
{
  path: 'resetpassword',
  loadChildren: () => import('./pages/reset_password/reset_password.module').then(m => m.ResetPasswordModule),
  canActivate : [AuthenticationService],
  data: { showHeader: false, showFooter: true, navbarItem: 'resetpassword' }
},
...

Get the error

ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(ResetPasswordModule)[UserService -> UserService -> ActivatedRouteSnapshot -> ActivatedRouteSnapshot -> ActivatedRouteSnapshot]: NullInjectorError: No provider for ActivatedRouteSnapshot!

Anybody could help me please ? Thanks in advance !

  • 1
    Have you injected RouterModule under imports in a top level module? ActivatedRoute/ActivatedRouteSnapshot are part of RouterModule and it's injected along with the routes in either a routing module or app.module. – Anjil Dhamala Dec 21 '21 at 16:24
  • Possibly related: [Unable to inject ActivatedRouteSnapshot](https://stackoverflow.com/questions/44205664/unable-to-inject-activatedroutesnapshot) – D M Dec 21 '21 at 16:26
  • @AnjilDhamala yes! I have imported it in the main module – Alberto Sanmartin Martinez Dec 21 '21 at 16:32

0 Answers0