Issue
I would like some help with troubleshooting an issue I have in my app. I am trying to create a functionality, that if the user is not loged in if he tries to access any url of the app he should be redirected to login.
I have created a auth guard but it somehow does not redirect me or users to www.my-domain.com/login but it rather stays on the www.my-domain.com/dashboard but it shows an empty page...
where is the issue in my code?
Here is the auth.service.ts code:
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;
}
Here is my auth.guard.ts code:
export const authGuard = () => {
const authService = inject(AuthenticationService);
const router = inject(Router);
if (authService.isLogedIn()) {
return true;
} else {
console.log('Not logen in');
return router.parseUrl('/login');
}
};
Here is my app-routing.module.ts code:
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 is my mistake? what could I have done diferently?
Solution
In your auth.guard.ts code:
Try this instead
else {
console.log('Not logen in');
return router.navigateByUrl('/login');
}
Answered By - Zoro
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.