Angular Routing and Guards

Viewed 78

For my Angular web application, I'm trying to achieve a basic routing process as follows;

  1. When the application launches, the opening page should be the Login page.
  2. When the user logs in, the next page displayed should be Landing page.
  3. If the session expires, the user should be redirected back to Login page.
  4. 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;

  1. 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".
  2. 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.
  3. 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.
  4. 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?

1 Answers

You need to use / before the route.

In "login.component.ts"

this.router.navigate(['/landing']);

In "auth.guard.ts"

this.router.navigateByUrl('/login');

Checkout more about relative link path.

Related