javascript - AuthGuard 和 RedirectTo 不适用于根路径

标签 javascript angular

我正在开发一个 Angular 应用程序,它具有以下URL路径

  • /(根目录)
  • /类(class)
  • /类(class)/创建
  • /类(class)/:id
  • /验证/登录

我已为除 auth/login 之外的所有路由添加了 AuthGuard。如果未经过身份验证,AuthGuard 会重定向到 auth\login

<小时/>

app-routing.module.ts

export const Approutes: Routes = [
  {
    path: '',
    canActivate: [AuthGuard],
    component: FullComponent,
    loadChildren: () => import('./pages/pages.module').then(m => m.PagesModule) // loading from pages-routing.ts
  },
  {
    path: 'auth',
    component: PlainComponent,
    children: [
      {
        path: '',
        pathMatch: 'full',
        redirectTo: 'login'
      },
      {
        path: 'login',
        component: LoginComponent
      }
    ]
  },
  {
    path: '**',
    redirectTo: ''
  }
];

pages-routing.ts

export const PagesRoutes: Routes = [
    {
        path: '',
        children: [
            {
                path: '',
                pathMatch: 'full',
                redirectTo: 'courses'
            },
            {
                path: 'courses',
                component: CourseMainPageComponent,
                data: {
                    title: 'My Courses'
                }
            },
            {
                path: 'courses/create',
                component: CourseCreatePageComponent,
                data: {
                    title: 'Create Course'
                }
            },
            {
                path: 'courses/:id',
                component: CourseShowPageComponent,
                data: {
                    title: 'Course Detail'
                }
            },
        ]
    }
];

问题

所有路由和 authGuard 工作正常。 但是当我输入根URL \时,我需要重定向到\courses,但它不起作用。 此外在根 URL \AuthGuard 甚至没有将我重定向到auth\login

NOTE I don't get any run-time or compile error.

最佳答案

您需要更改 pathMatch在您用于重定向的路由中将策略设置为 full。根据文档,

The path-match strategy 'full' matches against the entire URL. It is important to do this when redirecting empty-path routes. Otherwise, because an empty path is a prefix of any URL, the router would apply the redirect even when navigating to the redirect destination, creating an endless loop.

您的路线配置现在看起来像这样

export const PagesRoutes: Routes = [{
    path: '',
    children: [{
        path: '',
        redirectTo: 'courses',
        pathMatch: 'full'
    },
    // Add other routes here
    ]
}];

关于javascript - AuthGuard 和 RedirectTo 不适用于根路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61438187/

相关文章:

javascript - 如何在 ReactJS 的 ListView 中插入一个新项目

javascript - 触发angular2中元素的焦点

JavaScript 查找数组中的字符串是否可以在对象中找到

javascript - OrbitControls 在 Angular2 和 Three.js 中未定义

typescript - 使用 observables 跟踪 typeahead 列表中的当前位置

javascript - 使用javascript加载页面后将外部CSS应用于动态html

javascript - 在 Google Script 中转义花括号

javascript - 以 Angular 自动为页面的所有元素分配 ID

javascript - Angular2 Component 循环渲染 2 个 tr 元素

angular - 使用@Input 将异步值从父组件传递到子组件