Seeking assistance with troubleshooting an issue within my app. I am attempting to implement a feature where, if the user is not logged in and tries to access any URL of the app, they should be redirected to the login page.
I have set up an auth guard, but it doesn't seem to redirect me or other users to www.my-domain.com/login. Instead, it remains on www.my-domain.com/dashboard while displaying a blank page...
What could be wrong in my code?
Below is the snippet from auth.service.ts:
login(): Observable<User> {
const params = new HttpParams().append('param', 'value');
return this.http.get<User>(`${environment.apiUrl}someurl` + location.search, {params}).pipe(
tap((response: any) => {
if (response && response.token) {
localStorage.setItem('TOKEN_KEY', response.token);
localStorage.setItem('username',response.user_name);
localStorage.setItem('useremail',response.user_email);
this.setAuthToken(response.token);
this.isLoggedIn = true;
} else {
this.router.navigate(['/login']);
return;
}
}),
catchError(error => {
console.error('Error:', error);
return throwError(error);
})
);
}
isLogedIn() {
const token = localStorage.getItem('TOKEN_KEY');
return !!token;
}
Next, the portion from auth.guard.ts:
export const authGuard = () => {
const authService = inject(AuthenticationService);
const router = inject(Router);
if (authService.isLogedIn()) {
return true;
} else {
console.log('Not logged in');
return router.parseUrl('/login');
}
};
Finally, referring to my app-routing.module.ts:
const routes: Routes = [
{ path: '', redirectTo: '/login', pathMatch: 'full' },
{ path: 'login', component: LoginComponent, title: 'Login', },
{
path: 'dashboard',
component: DashboardComponent,
title: 'Dashboard',
canActivate: [authGuard],
canMatch: [() => localStorage.getItem('TOKEN_KEY') != null]
},
{
path: 'customers',
component: CustomersComponent,
title: 'Customers',
canActivate: [authGuard],
canMatch: [() => localStorage.getItem('TOKEN_KEY') != null]
},
{
path: 'customers/customers/:id',
component: CustomerComponent,
title: 'Customer',
canActivate: [authGuard],
canMatch: [() => localStorage.getItem('TOKEN_KEY') != null]
},
];
Where might the mistake lie? How could I have approached this differently?