For my Angular web application, I'm trying to achieve a basic routing process as follows;
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;
So I think I'm misunderstanding some parts about routing but couldn't find any answers yet. Any ideas how to resolve my issues?
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.