Angular 具有子组件默认路由的延迟加载模块

Angular lazy loaded module with child component default route

Angular 9.子组件没有加载懒加载模块组件。这是我的代码。

app-routing.module.ts

  {
    path: '',
    redirectTo: '/auth',
    pathMatch: 'full'
  },
  {
    path: 'auth',
    loadChildren: () => import('./pages/auth/auth.module').then(m => m.AuthModule),
  }

auth.module.ts

  {
    path: '',
    component: AuthRootComponent,
    children: [
      { path: 'login', component: LoginComponent},
      { path: 'forgot', component: ForgotPasswordComponent},
      { path: '', redirectTo: 'login', pathMatch: 'full' },
    ]
  }

当我使用 localhost:4200/ 时,它会将我重定向到 localhose:4200/auth。它不加载登录组件。

但是当我在浏览器中点击 url (localhost:4200/auth) 时,它将加载登录组件,并且需要新的 url url 即 localhost:4200/auth/login.

请告诉我,为什么在加载 auth 模块并且 url 是 localhost:4200 时它不从子数组加载登录? URL 应该是 localhost:4200/auth/login 但现在得到 url localhost:4200/auth

我认为您必须从 redirectTo: '/auth' 更改为 redirectTo: 'auth'。这是因为当您使用 绝对重定向 (例如 /auth)时,将只允许一个重定向操作,在本例中是转到 /auth 的那个,这意味着任何其他重定向(例如 redirectTo: 'login')将被忽略。

Here's 检查是否有任何绝对重定向:

if (allowRedirects && this.allowRedirects) {
    return this.expandSegmentAgainstRouteUsingRedirect(
      ngModule, segmentGroup, routes, route, paths, outlet);
}

here 是在绝对重定向之后,不能再有任何其他重定向的地方:

if (e instanceof AbsoluteRedirect) {
  // after an absolute redirect we do not apply any more redirects!
  this.allowRedirects = false;
  // we need to run matching, so we can fetch all lazy-loaded modules
  return this.match(e.urlTree);
}

绝对与相对重定向

摘自我的GH repo

redirectTo: 'foo/bar' redirectTo: '/foo/bar'的区别在于:

  • / - 将从根开始(第一个最外层的路由数组)
  • `` - 将从当前路由所在数组的第一条路由开始搜索