0

我有一个登录页面和一个延迟加载的模块,其子模块构成了应用程序中的大部分页面。这里看看 app-routing.module.ts

const routes: Routes = [{
    path: '',
    loadChildren: './main/main.module#MainModule'
  },
  {
    path: '',
    component: LoginLayoutComponent,
    children: [{
      path: 'login',
      component: LoginComponent
    }]
  },
  {
    path: '**',
    component: PageNotFoundComponent
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}

现在我有一个有几个子页面的主模块。我们来看看 main-routing.module.ts

onst routes: Routes = [{
  path: '',
  canActivate: [AuthGuard],
  component: LayoutComponent,
  children: [{
      path: '',
      redirectTo: 'home',
      pathMatch: 'full'
    },
    {
      path: 'home',
      component: HomeComponent
    },
    {
      path: 'user',
      loadChildren: './user/user.module#UserModule'
    },
    {
      path: 'dashboard',
      loadChildren: './dashboard/dashboard.module#DashboardModule'
    },
    {
      path: '**',
      component: PageNotFoundComponent
    }
  ]
}];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class MainRoutingModule {}

在 RouteGuard 中,如果用户未登录,我们将他们重定向到 /login

    this.router.navigate(['/login']);

问题是路由器试图path:'login'在 MainRoutingModule 的路由中查找,而“登录”实际上是 AppRoutingModule 路由的一部分。任何帮助,将不胜感激。

4

1 回答 1

1

我相信路由器正在您的应用程序路由模块中进行第一个匹配,您已将其指定为''. 然后它正在加载作为主路由模块的子模块。由于主路径和登录路径都相同 -''路由器永远不会进入第二个匹配项。考虑将登录父路由路径'login'和登录子路径设置为''.

编辑1:

看来路由器仍然匹配''主模块的路径值。考虑在主模块上方重新排序登录组件和/或向主模块的路径添加一个值,而不是空 - ''

顺便说一句,您基本上是懒惰地一次加载整个应用程序。随着时间的推移,您可能会考虑将所有这些子模块从主模块中拉出,并直接从 App Routing 模块延迟加载它们。(这也可以解决您的问题,因为您不会''在 App Routing 模块中有空的 - - 路径)。

当您使用空路径时''- 考虑添加每个Angular RoutepathMatch文档的策略,这样您就不会再次遇到这个问题,因为从技术上讲,每个根路径都会在任何其他后续段之前匹配一个空的 - 段(这同样的问题你是面对这里)。'full'''

编辑2:

const routes: Routes = [
  {
    path: 'login',
    component: LoginLayoutComponent,
    children: [{
      path: '',
      pathMatch: 'full',
      component: LoginComponent
    }]
  },
  {
    path: 'main',
    loadChildren: () => import('./main/main.module').then(m => m.MainModule)
  },
  {
    path: '**',
    component: PageNotFoundComponent
  }
];
于 2020-05-12T14:41:28.177 回答