延迟加载带有自己路由的ngModule

时间:2017-12-07 20:22:41

标签: angular angular-routing angular-router-loader

我有这种情况。

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

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

在代码中,这里:

auth.module.ts位于src/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延迟加载吗?怎么样?

1 个答案:

答案 0 :(得分:2)

延迟加载的模块未导入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]'