使用自己的路由延迟加载 ngModule

Lazy Loading ngModules with own routes

我有这个场景。

我有两个 Angular 模块:AuthModuleDashModule。这些模块中的每一个都有自己的 .routing.ts 文件。

然后,每个模块都被导入到应用级别的AppModule

在代码中,这里:

auth.module.tssrc/app/auth/auth.module.ts

auth.module.ts

import { NgModule } from '@angular/core';
... // all necessary imports
import { AuthRoutingModule } from './auth-module.routing';

@NgModule({
  imports: [
    CommonModule,
    AuthRoutingModule
  ],
  declarations: [
    // all declarations
  ],
  providers: []
})

export class AuthModule { }

src/app/auth/auth-module.routing.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
// all necessary imports

const routes: Routes = [
    { path: 'not-verified', component: NotVerifiedComponent },
    { path: 'login', component: LoginRegisterComponent },
    { path: 'register', component: LoginRegisterComponent },
    { path: 'verify-email/:token', component: VerifyEmailComponent },
    { path: 'reset-password/:token', component: ResetPasswordComponenet },
    { path: 'forgot', component: ForgotComponent },
  ];

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

DashModule 也遵循与 AuthModule

类似的模式

我的 src/app/app.routing.ts 看起来像这样:

import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { NotfoundComponent } from './pages/notfound/notfound.component';

const appRoutes: Routes = [ 
  // this is more like a catchall route. if all routes fail
  {path: '**', component: NotfoundComponent },
];

export const AppRouting: ModuleWithProviders = RouterModule.forRoot(appRoutes);

我的 src/app/app.module.ts 看起来像这样:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { AppRouting } from './app.routing';

import { AuthModule } from './auth/auth.module';
import { DashModule } from './dash/dash.module';
// Providers
// some providers

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    ...
    AuthModule,
    DashModule,
    AppRouting
  ],
  exports: [  ],
  providers: [
   // providers here
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

现在,我可以同时进行 DashModuleAuthModule 延迟加载吗?怎么样?

延迟加载的模块不会导入到 app.module。从那里删除它们,否则,它们将不会被延迟加载。在您的 app.routing.ts 中,您需要定义路由并使用以下内容延迟加载模块:

const appRoutes: Routes = [ 
  { path: 'dashbobard', loadChildren: 'src/app/dash/dashmodule.module#DashModule' },
  // or use relative paths.
  { path: 'auth', loadChildren: './auth/auth.module#AuthModule },
];

如果您将应用程序切换为延迟加载模块,您可能需要修复一些路由,例如 [routerLink]='[/some/route]'