8

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 ?

2 Answers 2

20

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.

11
  • After removing slash it stopped working after refreshing as well
    – Andayz
    Commented Aug 20, 2016 at 14:31
  • Did you include pathMatch: 'full'?
    – j2L4e
    Commented Aug 20, 2016 at 14:32
  • Yes, I added pathMatch
    – Andayz
    Commented Aug 20, 2016 at 14:33
  • I can't see why it wouldn't work. Does it work, when you remove the redirect route? I think you're being redirected to login whichever route you navigate to.
    – j2L4e
    Commented Aug 20, 2016 at 14:37
  • 1
    Would you mind marking this as the answer? Have a great day!
    – j2L4e
    Commented Aug 20, 2016 at 15:17
0

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.