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

时间:2016-12-31 15:25:20

标签: angular angular2-routing

尝试在我的angular2应用程序中创建我的重定向路由。

但我的问题是当有人进入像'nopath'这样的无效路径时,用户会被重定向到'HomeComponent',但网址仍保留'/#/ nopath'

我希望redirectTo路线也改变网址! 我该如何实现这个目标?

我应该在我的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: '' }
];

4 个答案:

答案 0 :(得分:4)

目前,我没有找到比攻击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;
  }
}

你们认为这可能是一个很好的解决方案吗?

答案 1 :(得分:0)

你应该试试这个,

const routes: Routes = [
  { path: '', pathMatch: 'full', redirectTo:'home'},  
   //<<<-----added redirectTo attribute

  { path: 'home', component: HomeComponent  },                
   //<<<----added this line


  { path: 'login', component: LoginComponent, canActivate: [AnonymousGuard] },
  { path: 'register', component: RegisterComponent, canActivate: [AnonymousGuard] },
  { path: 'users', component: UserComponent, canActivate: [AuthGuard] },

  { path: '**', component: HomeComponent }   //<<<--- updated line
];

答案 2 :(得分:0)

对我来说,此问题是由在AppModule中导入包含home组件的模块引起的。

答案 3 :(得分:-1)

也许为时已晚,但我认为问题应该是基础href标签。我在index.html中使用了类似下面的代码:

<head>
  <meta charset="utf-8">
  <title>MyCoolApp</title>
  <base href=".">
</head>

基本上使用href =“。”打破了路由。相反,如果你使用href =“/”来做这个伎俩。

<head>
  <meta charset="utf-8">
  <title>MyCoolApp</title>
  <base href="/">
</head>

所以现在路由工作,并且所有不匹配的路由将以“**”路径结束,并且因为“/”被用作基本URL以找到它们将被找到的* -bundle.js文件。我认为这就是为什么当你导航到“/”时,一切都会再次起作用。