Angular2重定向路由不会更改浏览器网址 [英] Angular2 Redirect route doesn't change browser url

查看:50
本文介绍了Angular2重定向路由不会更改浏览器网址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Trying to create my redirect route in my angular2 app.

但是我的问题是,当有人输入无效的路径(例如"nopath")时,用户将被重定向到"HomeComponent",但网址仍保留"/#/nopath"

But my problem is that when someone enter an invalid path like 'nopath' then user is redirected to the 'HomeComponent' but the url still keep the '/#/nopath'

我也希望redirectTo路由也更改url!我应该如何实现呢?

I want the redirectTo route to change the url too! How should i achieve this ?

我应该在我的HomeComponent构造函数中放置一个if来检查当前URL并将其路由更改为homecomponent吗?还是我想念的东西?

Should i put an if in my HomeComponent constructor that check the current url and change his route to homecomponent? Or there is something i'm missing?

路线:

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组件

Tried this, but i doesn't get the redirect to the home component

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 Router更好的方法.

For now, i didn't find any better way than hacking the Angular2 Router.

这是我的解决方案,这不是解决问题的绝妙方法……但至少它可以按我的意愿工作!

Here is my solution, it's not a beautifull way to fix the problem... but at least it work as i want!

路线:

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:

RedirectToHomeGuard:

@Injectable()
export class RedirectToHomeGuard implements CanActivate {

  constructor(private router: Router) { }

  canActivate() {
    this.router.navigate(['/']);
    return false;
  }
}

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

You guys think it could be a good solution?

这篇关于Angular2重定向路由不会更改浏览器网址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆