Angular2 重定向路由不会更改浏览器 url

标签 angular angular2-routing

尝试在我的 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/

相关文章:

Angular 2 嵌套可观察循环

angular - 使用选项时,Angular 中的 Google map 不显示 map

javascript - 如何在将值插入javascript中的数组时匹配键

angular - 如果 routerLink 具有绑定(bind),为什么 routerLinkActive 不触发?

javascript - 使用来自 Angular 中服务器的数据修补 FormArrays 值的问题

angular2-routing - 如何在 Bootstrap 中动态提供路由?

javascript - Angular 2函数在从API返回数据之前继续

validation - Angular 2 自定义验证器运行两次

没有 AUX URL 的 Angular 2 嵌套 View

angular - 如何检测用户在 Angular2 中导航回来?