For my Angular web application, I'm trying to achieve a basic routing process as follows;
- When the application launches, the opening page should be the Login page.
- When the user logs in, the next page displayed should be Landing page.
- If the session expires, the user should be redirected back to Login page.
- If user tries to open an unknown page, should be redirected to a 404 page.
Here is the code snippet from my "app-routing.module.ts";
const routes: Routes = [
{ path: 'login', component: LoginComponent },
{ path: 'landing', component: LandingComponent, canActivate: [AuthGuard]},
{ path: '', redirectTo: 'landing', pathMatch: 'full' },
{ path: '**', component: PageNotFoundComponent, pathMatch: 'full' }
];
This is my "login.component.ts";
this.authService.login(username, password).subscribe({
next: data => {
...
this.router.navigate(['landing']);
},
error: err => {
...
}
});
And this is the "auth.guard.ts";
canActivate(): boolean {
if (!this.tokenService.getToken()) {
this.router.navigateByUrl('login');
return false;
}
return true;
}
Here are the problems that I'm facing;
- When I launch the application (localhost:4200), it redirects me to Landing page, and since I don't have any session, AuthGuard then redirects me to Login page, ending up going to "http://localhost:4200/login". This is fine, but when I make a reload on this page, then it again follows the same process and ends up at "http://localhost:4200/login/login". My expectation is to land on Login page again with the url being "http://localhost:4200/login".
- When the user logs in, it redirects to the Landing page but now the url is "http://localhost:4200/login/landing", which I would expect to be "http://localhost:4200/landing" instead.
- When the session expires, it redirects to the Login page but the url is "http://localhost:4200/landing/login", which I would expect to be "http://localhost:4200/login" instead.
- Finally, when I try to go to an unknown page (lets say /unknown), it redirects to "http://localhost:4200/unknown/landing" and shows the Landing page, instead of 404 page.
So I think I'm misunderstanding some parts about routing but couldn't find any answers yet. Any ideas how to resolve my issues?