首页 > 解决方案 > 在一个具有不同组件的模块内实现角度延迟加载

问题描述

我正在尝试在我的测试应用程序中实现延迟加载。我有一个带有示例名称的 home/main/app 模块 - 电影。我创建了一个名为 Auth 的新模块,其中包含两个组件 - 注册和登录。我希望两个组件都被延迟加载。这是我在 app-routing.module.ts 中的示例代码

  const routes: Route[] = [
      { path: 'movies', component: MoviesComponent, resolve: { homepageMovies: HomepageMoviesResolver } },
      { path: 'movies/search', component: SearchedMoviesComponent },
      { path: 'movies/:id', component: MovieDetailsComponent, resolve: { singleMovie: SingleMovieResolver } },
      { path: 'register', loadChildren: () => import('./auth2/auth2.module').then(m=>m.Auth2Module) },
      { path: 'login', loadChildren: () => import('./auth2/auth2.module').then(m=>m.Auth2Module)},
      { path: '', pathMatch: 'full', redirectTo: 'movies' },
      { path: '**', component: PageNotFoundComponent },
      ];

还有我的 Auth 模块,实现了延迟加载:

 const routes: Routes = [
  { path: '', pathMatch: 'full', component: RegisterComponent },
  { path: '', pathMatch: 'full', component: LoginComponent }  
 ];

问题是当我导航到 http://localhost:4200/register 时,一切正常,我看到了注册表。但是,当我转到 http://localhost:4200/login 时,我再次看到相同的注册表单,并且带有它的表单的登录组件没有正确显示。知道如何解决这个问题吗?

标签: angularangular-routingangular-lazyloading

解决方案


这不是一个好方法。

只需按照以下方式进行

更新app.module

 const routes: Route[] = [
      { path: 'movies', component: MoviesComponent, resolve: { homepageMovies: HomepageMoviesResolver } },
      { path: 'movies/search', component: SearchedMoviesComponent },
      { path: 'movies/:id', component: MovieDetailsComponent, resolve: { singleMovie: SingleMovieResolver } },
      { path: 'auth', loadChildren: () => import('./auth2/auth2.module').then(m=>m.Auth2Module) },
      { path: '', pathMatch: 'full', redirectTo: 'movies' },
      { path: '**', component: PageNotFoundComponent },
      ];

并且auth2.module作为

const routes: Routes = [
 { path: 'register', pathMatch: 'full', component: RegisterComponent },
 { path: 'login', pathMatch: 'full', component: LoginComponent }  
];

现在访问registrationpage ashttp://localhost:4200/auth/registerloginpage ashttp://localhost:4200/auth/login


推荐阅读