I have a basic auth guard defined like this:
export function authenticationGuard(): CanActivateFn {
return () => {
const authService: AuthService = inject(AuthService);
if (authService.hasAccess() ) {
return true;
}
const router: Router = inject(Router);
router.navigate(['/login']);
return false;
};
}
/* Another way, not working as well */
@Injectable({ providedIn: 'root' })
export class AuthGuard {
constructor(private router: Router, private authService: AuthService) {}
canActivate(): boolean {
if (this.authService.hasAccess() ) {
return true;
}
this.router.navigate(['/login']);
return false;
}
}
And my AuthService is defined like so:
@Injectable({ providedIn: 'root' })
export class AuthService extends BaseService {
accessToken?: string;
refreshToken?: string;
constructor(http: HttpClient) {
super(http, 'auth');
}
hasAccess(): boolean {
return !!this.refreshToken;
}
signIn(email: string, password: string) {
return super.post<AuthResult>('signin', { email, password }).pipe(tap(this.storeToken));
}
private storeToken(result: AuthResult) {
this.accessToken = result.accessToken;
this.refreshToken = result.refreshToken;
}
}
The guard is currently only used in one route defined in AppRoutingModule:
const routes: Routes = [
{
path: 'account',
loadChildren: () => import('./views/account/account.routes').then(t => t.routes),
canActivate: [authenticationGuard()]
//canActivate: [AuthGuard] /* Not working as well */
//canActivate: [() => inject(AuthGuard).canActivate()] /* Not working as well */
}
]
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule {}
And the AppModule:
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule,
AppRoutingModule,
AppStoreModule,
LoggerModule.forRoot({
serverLoggingUrl: '/api/logs',
level: NgxLoggerLevel.TRACE,
disableConsoleLogging: !isDevMode(),
serverLogLevel: NgxLoggerLevel.OFF
}),
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi: true
}
],
bootstrap: [AppComponent]
})
export class AppModule { }
How can I make sure that it will load the global root'ed AuthService instance?
The problem isn't that it's not working, but that it's not returning the same AuthService instance that would be returned if I got the service via constructor reference.