尝试在我的 angular2 应用程序中创建我的重定向路由。
但我的问题是,当有人输入像“nopath”这样的无效路径时,用户将被重定向到“HomeComponent”,但 url 仍然保留“/#/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});
编辑:
试过了,但我没有得到到 home 组件的重定向
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: '' }
];
最佳答案
目前,我没有找到比破解 Angular2 路由器更好的方法。
这是我的解决方案,这不是解决问题的好方法...但至少它能按我的意愿工作!
路线:
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: '**', component: HomeComponent, canActivate: [RedirectToHomeGuard] }
];
export const routing: ModuleWithProviders = RouterModule.forRoot(routes, { useHash: true });
RedirectToHomeGuard:
@Injectable()
export class RedirectToHomeGuard implements CanActivate {
constructor(private router: Router) { }
canActivate() {
this.router.navigate(['/']);
return false;
}
}
你们认为这可能是一个好的解决方案吗?
关于Angular2 重定向路由不会更改浏览器 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41409578/