简体   繁体   English

Angular 2 redirectTo与路由器无法正常工作

[英]Angular 2 redirectTo with router not work

I am developing my first app using angular 2 and I encountered strange problem. 我正在使用角度2开发我的第一个应用程序,我遇到了奇怪的问题。

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. 当我输入localhost:3000时,我会自动重定向到我的localhost:3000 / login,这是我的登录表单页面。 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. 当我输入我的凭据并单击提交路由器naviagation不起作用(控制台中没有错误),但令人惊讶的是当我刷新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 ? 这种路线配置有什么问题?

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. 您还可能需要在重定向路由上设置pathMatch: 'full'属性。

{ path: '', redirectTo: 'login', pathMatch: 'full' }

Otherwise your route doesn't trigger when there are other routes with a deeper level available. 否则,当存在具有更深级别的其他路线时,您的路线不会触发。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM