Reputation: 155
I am developing my first app using angular 2 and I encountered strange problem.
I have my routes configuration like this:
export const routes: RouterConfig = [
{ path: '', redirectTo: 'login' },
{ path: 'login', component: Login },
{ path: 'home', component: Home }
];
and when I enter localhost:3000 I am automatically redirected to my localhost:3000/login , which is my login form page. When I enter my credentials and click submit router naviagation doesn't work ( no errors in console ), but suprisingly router works when I refresh localhost:3000/login.
I call router this way:
export class Login {
constructor(public router: Router, public http: Http) {
}
login(event, username, password) {
event.preventDefault();
// ...
this.router.navigate(['/home']);
}
}
What could be wrong with this routes configurations ?
Upvotes: 9
Views: 31096
Reputation: 21
In Angular 15, redirectTo will not work alone without pathMatch property. It tells angular to redirect to the default path or named component when the path doesn't match with other routes.
Upvotes: 0
Reputation: 7060
You have to omit the leading slash:
this.router.navigate(['home']);
Also you might need to set the pathMatch: 'full'
property on your redirect route.
{ path: '', redirectTo: 'login', pathMatch: 'full' }
Otherwise your route doesn't trigger when there are other routes with a deeper level available.
Upvotes: 20