首页 > 解决方案 > 使用 Angular 延迟加载模块设置默认路由

问题描述

我用 Angular 延迟加载模块,但是如果我导航到 URL 而不提供路由路径,例如http://localhost:4200它会about.module在我期望加载的时候加载我的home.module。急切地加载模块按预期工作。

每个模块都有一个*-routing.module

应用程序路由.module.ts

/* ... */

const routes: Routes = [
  {
    path: 'home',
    loadChildren: () => import('./modules/home/home.module').then(m => m.HomeModule)
  },
  {
    path: 'about',
    loadChildren: () => import('./modules/about/about.module').then(m => m.AboutModule)
  },
  {
    path: '',
    redirectTo: 'home',
    pathMatch: 'full'
  },
  {
    path: '**',
    redirectTo: 'page-not-found'
  }
];

@NgModule({
  imports: [
    RouterModule.forRoot(
      routes
      /* ... */
    )
  ],
  exports: [RouterModule]
})

/* ... */

家庭路由.module.ts

/* ... */

const routes: Routes = [
  {
    path: '',
    component: HomeComponent,
    data: {
      title: 'Home'
    }
  }
];

@NgModule({
  imports: [
    /* ... */
    RouterModule.forChild(routes)
  ],
  exports: [RouterModule]
})

/* ... */

about-routing.module.ts

/* ... */

const routes: Routes = [
  {
    path: '',
    component: AboutComponent,
    data: {
      title: 'About'
    }
  }
];

@NgModule({
  imports: [
    /* ... */
    RouterModule.forChild(routes)
  ],
  exports: [RouterModule]
})

/* ... */

我尝试过并且适用于旧版本 Angular 的其他解决方案似乎不起作用:

在这种情况下,我正在使用 Angular 8+。

标签: angularlazy-loading

解决方案


非常及时,因为我在从 7.2.5 升级到 8.1.3 后似乎遇到了同样的问题。在我非常确定它进行了重定向之后,它工作得很好,在过去的 12-24 小时之后,一些事情无意中改变了我觉得我疯了的地方。如果我直接进入 /home 没有问题,但 localhost:4200 不会重定向,但没有任何错误。

app.module.ts

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    RouterModule.forRoot([
      { path: '', redirectTo: 'home', pathMatch: 'full' },
      { path: 'home', loadChildren: () => import(`./shell/home/home.module`).then(m => m.HomeModule) }
    ]),

home.module.ts

import { HomeComponent } from './home.component';
import { NgModule, NO_ERRORS_SCHEMA } from '@angular/core';
import { HomeRoutingModule } from './home-routing-module';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';

@NgModule({
  imports: [
    CommonModule,
    HomeRoutingModule
  ],
  declarations: [
      HomeComponent
  ],
  exports: [RouterModule],
  schemas: [ NO_ERRORS_SCHEMA ]
})
export class HomeModule { }

家庭路由模块.ts

import { Routes } from '@angular/router';
import { RouterModule } from '@angular/router';

import { HomeComponent } from './home.component';
import { NgModule } from '@angular/core';

const routes: Routes = [
    { path: '', component: HomeComponent }
];

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

推荐阅读