I was using CanActivate
, but I recently migrated to Angular 16 and since it is deprecated, I tried to use inject()
as guided by the official documentation.
This is how my routing component looks like:
const routes: Routes = [
{
path: '',
component: ContainerComponent,
canActivate: [() => inject(MyGuard).canActivate()]
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class RoutingModuleComponent { }
This is how my Guard component looks like:
@Injectable({ providedIn: 'root' })
export class MyGuard {
canActivate(): boolean {
return true; // this value is based on a variable
}
}
But now I'm getting this error message while navigating to this:
NullInjectorError: R3InjectorError(M)[At -> At -> At]:
NullInjectorError: No provider for At!
NullInjectorError: R3InjectorError(M)[At -> At -> At]:
NullInjectorError: No provider for At!
at sp.get (main)
at Dc.get (main)
at Dc.get (main)
at Dc.get (main)
at ti.get (main)
at Ur (main)
at ya (main)
at Object.Xl (main)
at Jr.#t.ɵfac [as factory] (7)
I also tried to adding this method in the MyGaurd class like this, and used in canActivate of routes:
export const AuthGuard: CanActivateFn = (): boolean => {
return inject(MyGuard).canActivate();
};
But it also throws the same error message as above.
- Updating the route definition to be a function like
canActivate: [() => inject(MyGuard).canActivate()]
- Tried Using
CanActivateFn
instead.