简体   繁体   English

Angular 路由器无限循环与 canActivate / redirectTo

[英]Angular Router endless loop with canActivate / redirectTo

I'm having trouble getting a redirect in my routing module working, and adding an AuthGuard in CanActivate complicates it even further.我无法在我的路由模块中获得重定向,并且在 CanActivate 中添加 AuthGuard 会使它更加复杂。 Here is a simplified router:这是一个简化的路由器:

const routes: Routes = [
  {
    path: 'login',
    component: LoginComponent,
  },
  {
    path: 'home',
    component: HomeComponent,
  },
  {
    path: 'secret',
    component: SecretComponent,
    canActivate: [ AuthGuard ]
  },
  { path: '', redirectTo: '/home', pathMatch: 'full' },
];

With this current setup, I get some strange behavior.使用当前的设置,我得到了一些奇怪的行为。 Every route is considered a child of the path: '' route, so going to '' brings you to '/home'.每条路由都被认为是路径的一个子path: ''路由,所以去 '' 会把你带到 '/home'。 If I refresh the page, I go to '/home/home'.如果我刷新页面,我 go 到“/home/home”。 This goes for login as well - navigation to '/login' will actually take you to '/login/home'.这也适用于登录 - 导航到“/login”实际上会将您带到“/login/home”。 If you refresh any of these pages after the extra '/home' has been tacked onto the end, it causes the page to error out.如果在将额外的“/home”附加到末尾之后刷新这些页面中的任何一个,则会导致页面出错。

The authguard is just another complication, what with it navigating the user around based on authentication status. authguard 只是另一个复杂功能,它根据身份验证状态导航用户。

Things I have tried:我尝试过的事情:

  • Removing the authguard删除 authguard
  • Changing the order of the path declarations更改路径声明的顺序
  • Having only a single path + black path redirecting to it只有一条路径+黑色路径重定向到它
  • pathMatch: 'prefix'

I'm comparing this to some functioning production projects, example tutorials, etc. Everything seems to be in place.我将其与一些正常运行的生产项目、示例教程等进行比较。一切似乎都已到位。 Not sure what's going wrong.不知道出了什么问题。

Try setting up your routes like this:尝试像这样设置您的路线:

const routes: Routes = [
    { path: 'login', component: LoginComponent, },
    { path: 'home', component: HomeComponent, },
    {
        path: 'secret',
        component: SecretComponent,
        canActivate: [ AuthGuard ]
    },
    { path: '**', redirectTo: '/home' },
];

Don't redirect from '' just redirect from '**' .不要从''重定向,只需从'**'重定向。 You don't seem to want anything to show if the path is just https://example.com/ , so don't include a route for that -- '**' will pick it up.如果路径只是https://example.com/ ,您似乎不希望显示任何内容,因此不要包含该路径 - '**'会选择它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM