【发布时间】:2017-05-15 13:00:56
【问题描述】:
尝试在我的 angular2 应用程序中创建重定向路线。
但我的问题是,当有人输入像“nopath”这样的无效路径时,用户会被重定向到“HomeComponent”,但网址仍然保留“/#/nopath”
我也想要redirectTo 路由来改变url! 我应该如何做到这一点?
我应该在我的 HomeComponent 构造函数中添加一个 if 来检查当前 url 并更改他到 homecomponent 的路由吗?还是我缺少什么?
路线:
const routes: Routes = [
{ path: '', pathMatch: 'full', component: HomeComponent },
{ path: 'login', component: LoginComponent, canActivate: [AnonymousGuard] },
{ path: 'register', component: RegisterComponent, canActivate: [AnonymousGuard] },
{ path: 'users', component: UserComponent, canActivate: [AuthGuard] },
{ path: '**', redirectTo: '' }
];
export const routing: ModuleWithProviders = RouterModule.forRoot(routes, {useHash: true});
编辑:
试过了,但我没有重定向到主组件
const routes: Routes = [
{ path: '', pathMatch: 'full' , redirectTo: 'home' },
{ path: 'home', component: HomeComponent },
{ path: 'login', component: LoginComponent, canActivate: [AnonymousGuard] },
{ path: 'register', component: RegisterComponent, canActivate: [AnonymousGuard] },
{ path: 'users', component: UserComponent, canActivate: [AuthGuard] },
{ path: '**', redirectTo: '' }
];
【问题讨论】:
-
可能不使用重定向路由,只使用“**”,组件:HomeComponent(而不是重定向)。 (NM 尝试了几种方法,是的,我不会这样做)。
-
您使用的是最新的 Angular2 和路由器版本吗?我看到最近提到的一个类似问题,更新解决了它。
-
我用的是3.2.3版本的路由器,不知道怎么查看是否是最新版本
-
检查 GitHub 存储库中的
CHANGELOG.md -
我不确定是否理解路由器 CHANGELOG.md 中的版本:github.com/angular/angular/blob/master/modules/%40angular/… 它说 3.0.0 - RC2 但我使用的是 3.2.3 版本,所以有些东西不在版本!