Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 redirectTo with router not work

Tags:

angular

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 ?

like image 942
Andayz Avatar asked Aug 20 '16 14:08

Andayz


Video Answer


1 Answers

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.

like image 191
j2L4e Avatar answered Oct 21 '22 21:10

j2L4e