填写这份《一分钟调查》,帮我们(开发组)做得更好!去填写Home

惰性加载特性模块

Lazy-loading feature modules

默认情况下,NgModule 都是急性加载的,也就是说它会在应用加载时尽快加载,所有模块都是如此,无论是否立即要用。对于带有很多路由的大型应用,考虑使用惰性加载 —— 一种按需加载 NgModule 的模式。惰性加载可以减小初始包的尺寸,从而减少加载时间。

By default, NgModules are eagerly loaded, which means that as soon as the app loads, so do all the NgModules, whether or not they are immediately necessary. For large apps with lots of routes, consider lazy loading—a design pattern that loads NgModules as needed. Lazy loading helps keep initial bundle sizes smaller, which in turn helps decrease load times.

如果需要本页描述的具有两个惰性加载模块的范例应用,参阅现场演练 / 下载范例

For the final sample app with two lazy-loaded modules that this page describes, see the现场演练 / 下载范例.

惰性加载入门

Lazy loading basics

本节会介绍配置惰性加载路由的基本过程。 想要一个分步的范例,参阅本页的分步设置部分。

This section introduces the basic procedure for configuring a lazy-loaded route. For a step-by-step example, see the step-by-step setup section on this page.

要惰性加载 Angular 模块,请在 AppRoutingModule routes 中使用 loadChildren 代替 component 进行配置,代码如下。

To lazy load Angular modules, use loadChildren (instead of component) in your AppRoutingModule routes configuration as follows.

AppRoutingModule (excerpt)
      
      const routes: Routes = [
  {
    path: 'items',
    loadChildren: () => import('./items/items.module').then(m => m.ItemsModule)
  }
];
    

在惰性加载模块的路由模块中,添加一个指向该组件的路由。

In the lazy-loaded module's routing module, add a route for the component.

Routing module for lazy loaded module (excerpt)
      
      const routes: Routes = [
  {
    path: '',
    component: ItemsComponent
  }
];
    

还要确保从 AppModule 中移除了 ItemsModule。 想要一个关于惰性加载模块的分步操作指南,请继续查看本页的后续章节。

Also be sure to remove the ItemsModule from the AppModule. For step-by-step instructions on lazy loading modules, continue with the following sections of this page.

分步设置

Step-by-step setup

建立惰性加载的特性模块有两个主要步骤:

There are two main steps to setting up a lazy-loaded feature module:

  1. 使用 --route 标志,用 CLI 创建特性模块。

    Create the feature module with the CLI, using the --route flag.

  2. 配置相关路由。

    Configure the routes.

建立应用

Set up an app

如果你还没有应用,可以遵循下面的步骤使用 CLI 创建一个。如果已经有了,可以直接跳到 配置路由部分。 输入下列命令,其中的 customer-app 表示你的应用名称:

If you don’t already have an app, you can follow the steps below to create one with the CLI. If you already have an app, skip to Configure the routes. Enter the following command where customer-app is the name of your app:

      
      ng new customer-app --routing
    

这会创建一个名叫 customer-app 的应用,而 --routing 标识生成了一个名叫 app-routing.module.ts 的文件,它是你建立惰性加载的特性模块时所必须的。 输入命令 cd customer-app 进入该项目。

This creates an app called customer-app and the --routing flag generates a file called app-routing.module.ts, which is one of the files you need for setting up lazy loading for your feature module. Navigate into the project by issuing the command cd customer-app.

--routing 选项需要 Angular/CLI 8.1 或更高版本。 请参阅保持最新

The --routing option requires Angular/CLI version 8.1 or higher. See Keeping Up to Date.

创建一个带路由的特性模块

Create a feature module with routing

接下来,你将需要一个包含路由的目标组件的特性模块。 要创建它,在终端中输入如下命令,其中 customers 是特性模块的名称。加载 customers 特性模块的路径也是 customers,因为它是通过 --route 选项指定的:

Next, you’ll need a feature module with a component to route to. To make one, enter the following command in the terminal, where customers is the name of the feature module. The path for loading the customers feature modules is also customers because it is specified with the --route option:

      
      ng generate module customers --route customers --module app.module
    

这将创建一个 customers 文件夹,在其 customers.module.ts 文件中定义了新的可惰性加载模块 CustomersModule。该命令会自动在新特性模块中声明 CustomersComponent

This creates a customers folder having the new lazy-loadable feature module CustomersModule defined in the customers.module.ts file and the routing module CustomersRoutingModule defined in the customers-routing.module.ts file. The command automatically declares the CustomersComponent and imports CustomersRoutingModule inside the new feature module.

因为这个新模块想要惰性加载,所以该命令不会在应用的根模块 app.module.ts 中添加对新特性模块的引用。 相反,它将声明的路由 customers 添加到以 --module 选项指定的模块中声明的 routes 数组中。

Because the new module is meant to be lazy-loaded, the command does NOT add a reference to the new feature module in the application's root module file, app.module.ts. Instead, it adds the declared route, customers to the routes array declared in the module provided as the --module option.

src/app/app-routing.module.ts
      
      const routes: Routes = [
  {
    path: 'customers',
    loadChildren: () => import('./customers/customers.module').then(m => m.CustomersModule)
  }
];
    

注意,惰性加载语法使用 loadChildren,其后是一个使用浏览器内置的 import('...') 语法进行动态导入的函数。 其导入路径是到当前模块的相对路径。

Notice that the lazy-loading syntax uses loadChildren followed by a function that uses the browser's built-in import('...') syntax for dynamic imports. The import path is the relative path to the module.

String-based lazy loading

在 Angular 版本 8 中,loadChildren 路由规范的字符串语法已弃用,建议改用 import() 语法。不过,你仍然可以通过在 tsconfig 文件中包含惰性加载的路由来选择使用基于字符串的惰性加载(loadChildren: './path/to/module#Module'),这样它就会在编译时包含惰性加载的文件。

In Angular version 8, the string syntax for the loadChildren route specification was deprecated in favor of the import() syntax. However, you can opt into using string-based lazy loading (loadChildren: './path/to/module#Module') by including the lazy-loaded routes in your tsconfig file, which includes the lazy-loaded files in the compilation.

默认情况下,会用 CLI 生成项目,这些项目将更严格地包含旨在与 import() 语法一起使用的文件。

By default the CLI will generate projects with stricter file inclusions intended to be used with the import() syntax.

添加另一个特性模块

Add another feature module

使用同样的命令创建第二个带路由的惰性加载特性模块及其桩组件。

Use the same command to create a second lazy-loaded feature module with routing, along with its stub component.

      
      ng generate module orders --route orders --module app.module
    

这将创建一个名为 orders 的新文件夹,其中包含 OrdersModuleOrdersRoutingModule 以及新的 OrdersComponent 源文件。 使用 --route 选项指定的 orders 路由,用惰性加载语法添加到了 app-routing.module.ts 文件内的 routes 数组中。

This creates a new folder called orders containing the OrdersModule and OrdersRoutingModule, along with the new OrdersComponent source files. The orders route, specified with the --route option, is added to the routes array inside the app-routing.module.ts file, using the lazy-loading syntax.

src/app/app-routing.module.ts
      
      const routes: Routes = [
  {
    path: 'customers',
    loadChildren: () => import('./customers/customers.module').then(m => m.CustomersModule)
  },
  {
    path: 'orders',
    loadChildren: () => import('./orders/orders.module').then(m => m.OrdersModule)
  }
];
    

建立 UI

Set up the UI

虽然你也可以在地址栏中输入 URL,不过导航 UI 会更好用,也更常见。 把 app.component.html 中的占位脚本替换成一个自定义的导航,以便你在浏览器中能轻松地在模块之间导航。

Though you can type the URL into the address bar, a navigation UI is easier for the user and more common. Replace the default placeholder markup in app.component.html with a custom nav so you can easily navigate to your modules in the browser:

app.component.html
      
      <h1>
  {{title}}
</h1>

<button routerLink="/customers">Customers</button>
<button routerLink="/orders">Orders</button>
<button routerLink="">Home</button>

<router-outlet></router-outlet>
    

要想在浏览器中看到你的应用,就在终端窗口中输入下列命令:

To see your app in the browser so far, enter the following command in the terminal window:

      
      ng serve
    

然后,跳转到 localhost:4200,这时你应该看到 "customer-app" 和三个按钮。

Then go to localhost:4200 where you should see "customer-app" and three buttons.

这些按钮生效了,因为 CLI 会自动将特性模块的路由添加到 app.module.ts 中的 routes 数组中。

These buttons work, because the CLI automatically added the routes to the feature modules to the routes array in app.module.ts.

导入与路由配置

Imports and route configuration

CLI 会将每个特性模块自动添加到应用级的路由映射表中。 通过添加默认路由来最终完成这些步骤。 在 app-routing.module.ts 文件中,使用如下命令更新 routes 数组:

The CLI automatically added each feature module to the routes map at the application level. Finish this off by adding the default route. In the app-routing.module.ts file, update the routes array with the following:

src/app/app-routing.module.ts
      
      const routes: Routes = [
  {
    path: 'customers',
    loadChildren: () => import('./customers/customers.module').then(m => m.CustomersModule)
  },
  {
    path: 'orders',
    loadChildren: () => import('./orders/orders.module').then(m => m.OrdersModule)
  },
  {
    path: '',
    redirectTo: '',
    pathMatch: 'full'
  }
];
    

前两个路径是到 CustomersModuleOrdersModule 的路由。 最后一个条目则定义了默认路由。空路径匹配所有不匹配先前路径的内容。

The first two paths are the routes to the CustomersModule and the OrdersModule. The final entry defines a default route. The empty path matches everything that doesn't match an earlier path.

特性模块内部

Inside the feature module

接下来,仔细看看 customers.module.ts 文件。如果你使用的是 CLI,并按照此页面中的步骤进行操作,则无需在此处执行任何操作。

Next, take a look at the customers.module.ts file. If you’re using the CLI and following the steps outlined in this page, you don’t have to do anything here.

src/app/customers/customers.module.ts
      
      import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { CustomersRoutingModule } from './customers-routing.module';
import { CustomersComponent } from './customers.component';

@NgModule({
  imports: [
    CommonModule,
    CustomersRoutingModule
  ],
  declarations: [CustomersComponent]
})
export class CustomersModule { }
    

customers.module.ts 文件导入了 customers-routing.module.tscustomers.component.ts 文件。@NgModuleimports 数组中列出了 CustomersRoutingModule,让 CustomersModule 可以访问它自己的路由模块。CustomersComponent 位于 declarations 数组中,这意味着 CustomersComponent 属于 CustomersModule

The customers.module.ts file imports the customers-routing.module.ts and customers.component.ts files. CustomersRoutingModule is listed in the @NgModule imports array giving CustomersModule access to its own routing module. CustomersComponent is in the declarations array, which means CustomersComponent belongs to the CustomersModule.

然后,app-routing.module.ts 会使用 JavaScript 的动态导入功能来导入特性模块 customers.module.ts

The app-routing.module.ts then imports the feature module, customers.module.ts using JavaScript's dynamic import.

专属于特性模块的路由定义文件 customers-routing.module.ts 将导入在 customers.component.ts 文件中定义的自有特性组件,以及其它 JavaScript 导入语句。然后将空路径映射到 CustomersComponent

The feature-specific route definition file customers-routing.module.ts imports its own feature component defined in the customers.component.ts file, along with the other JavaScript import statements. It then maps the empty path to the CustomersComponent.

src/app/customers/customers-routing.module.ts
      
      import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { CustomersComponent } from './customers.component';


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

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

这里的 path 设置为空字符串,因为 AppRoutingModule 中的路径已经设置为 customers,因此,CustomersRoutingModule 中的此路由已经位于 customers 这个上下文中。此路由模块中的每个路由都是其子路由。

The path here is set to an empty string because the path in AppRoutingModule is already set to customers, so this route in the CustomersRoutingModule, is already within the customers context. Every route in this routing module is a child route.

另一个特性模块中路由模块的配置也类似。

The other feature module's routing module is configured similarly.

src/app/orders/orders-routing.module.ts (excerpt)
      
      import { OrdersComponent } from './orders.component';

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

确认它工作正常

Verify lazy loading

你可以使用 Chrome 开发者工具来确认一下这些模块真的是惰性加载的。 在 Chrome 中,按 Cmd+Option+i(Mac)或 Ctrl+Shift+j(PC),并选中 Network 页标签。

You can check to see that a module is indeed being lazy loaded with the Chrome developer tools. In Chrome, open the dev tools by pressing Cmd+Option+i on a Mac or Ctrl+Shift+j on a PC and go to the Network Tab.

点击 Orders 或 Customers 按钮。如果你看到某个 chunk 文件出现了,就表示一切就绪,特性模块被惰性加载成功了。Orders 和 Customers 都应该出现一次 chunk,并且它们各自只应该出现一次。

Click on the Orders or Customers button. If you see a chunk appear, everything is wired up properly and the feature module is being lazy loaded. A chunk should appear for Orders and for Customers but will only appear once for each.

要想再次查看它或测试本项目后面的行为,只要点击 Network 页左上放的 清除 图标即可。

To see it again, or to test after working in the project, clear everything out by clicking the circle with a line through it in the upper left of the Network Tab:

然后,使用 Cmd+r(Mac) 或 Ctrl+r(PC) 重新加载页面。

Then reload with Cmd+r or Ctrl+r, depending on your platform.

forRoot()forChild()

forRoot() and forChild()

你可能已经注意到了,CLI 会把 RouterModule.forRoot(routes) 添加到 AppRoutingModuleimports 数组中。 这会让 Angular 知道 AppRoutingModule 是一个路由模块,而 forRoot() 表示这是一个根路由模块。 它会配置你传入的所有路由、让你能访问路由器指令并注册 RouterforRoot() 在应用中只应该使用一次,也就是这个 AppRoutingModule 中。

You might have noticed that the CLI adds RouterModule.forRoot(routes) to the AppRoutingModule imports array. This lets Angular know that the AppRoutingModule is a routing module and forRoot() specifies that this is the root routing module. It configures all the routes you pass to it, gives you access to the router directives, and registers the Router service. Use forRoot() only once in the application, inside the AppRoutingModule.

CLI 还会把 RouterModule.forChild(routes) 添加到各个特性模块中。这种方式下 Angular 就会知道这个路由列表只负责提供额外的路由并且其设计意图是作为特性模块使用。你可以在多个模块中使用 forChild()

The CLI also adds RouterModule.forChild(routes) to feature routing modules. This way, Angular knows that the route list is only responsible for providing additional routes and is intended for feature modules. You can use forChild() in multiple modules.

forRoot() 方法为路由器管理全局性的注入器配置。 forChild() 方法中没有注入器配置,只有像 RouterOutletRouterLink 这样的指令。 欲知详情,参阅单例服务章的 forRoot() 模式小节。

The forRoot() method takes care of the global injector configuration for the Router. The forChild() method has no injector configuration. It uses directives such as RouterOutlet and RouterLink. For more information, see the forRoot() pattern section of the Singleton Services guide.

预加载

Preloading

预加载通过在后台加载部分应用来改进用户体验。你可以预加载模块或组件数据。

Preloading improves UX by loading parts of your app in the background. You can preload modules or component data.

预加载模块

Preloading modules

预加载模块通过在后台加载部分应用来改善用户体验,这样用户在激活路由时就无需等待下载这些元素。

Preloading modules improves UX by loading parts of your app in the background so users don't have to wait for the elements to download when they activate a route.

要启用所有惰性加载模块的预加载,请从 Angular 的 router 导入 PreloadAllModules 令牌。

To enable preloading of all lazy loaded modules, import the PreloadAllModules token from the Angular router.

AppRoutingModule (excerpt)
      
      import { PreloadAllModules } from '@angular/router';
    

还是在 AppRoutingModule 中,通过 forRoot() 指定你的预加载策略。

Still in the AppRoutingModule, specify your preloading strategy in forRoot().

AppRoutingModule (excerpt)
      
      RouterModule.forRoot(
  appRoutes,
  {
    preloadingStrategy: PreloadAllModules
  }
)
    

预加载组件数据

Preloading component data

要预加载组件数据,你可以使用 resolver 守卫。解析器通过阻止页面加载来改进用户体验,直到显示页面时的全部必要数据都可用。

To preload component data, you can use a resolver. Resolvers improve UX by blocking the page load until all necessary data is available to fully display the page.

解析器

Resolvers

创建一个解析器服务。通过 CLI,生成服务的命令如下:

Create a resolver service. With the CLI, the command to generate a service is as follows:

      
      ng generate service 

    

在你的服务中,导入下列路由器成员,实现 Resolve 接口,并注入到 Router 服务中:

In your service, import the following router members, implement Resolve, and inject the Router service:

Resolver service (excerpt)
      
      import { Resolve } from '@angular/router';

...

export class CrisisDetailResolverService implements Resolve<> {
  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<> {
    // your logic goes here
  }
}
    

把这个解析器导入此模块的路由模块。

Import this resolver into your module's routing module.

Feature module's routing module (excerpt)
      
      import { YourResolverService }    from './your-resolver.service';
    

在组件的 route 配置中添加一个 resolve 对象。

Add a resolve object to the component's route configuration.

Feature module's routing module (excerpt)
      
      {
  path: '/your-path',
  component: YourComponent,
  resolve: {
    crisis: YourResolverService
  }
}
    

在此组件中,使用一个 Observable 来从 ActivatedRoute 获取数据。

In the component, use an Observable to get the data from the ActivatedRoute.

Component (excerpt)
      
      ngOnInit() {
  this.route.data
    .subscribe((your-parameters) => {
      // your data-specific code goes here
    });
}
    

关于工作范例的更多信息,请参阅路由教程的预加载部分

For more information with a working example, see the routing tutorial section on preloading.

对惰性加载模块进行故障排除

Troubleshooting lazy-loading modules

惰性加载模块时常见的错误之一,就是在应用程序中的多个位置导入通用模块。你可以通过首先使用 Angular CLI 生成模块并包括 --route route-name 参数来测试这种情况,其中 route-name 是模块的名称。接下来,生成不带 --route 参数的模块。如果你用了--route 参数,Angular CLI 就会生成错误,但如果不使用它便可以正确运行,则可能是在多个位置导入了相同的模块。

A common error when lazy-loading modules is importing common modules in multiple places within an application. You can test for this condition by first generating the module using the Angular CLI and including the --route route-name parameter, where route-name is the name of your module. Next, generate the module without the --route parameter. If the Angular CLI generates an error when you use the --route parameter, but runs correctly without it, you may have imported the same module in multiple places.

请记住,许多常见的 Angular 模块都应该导入应用的基础模块中。

Remember, many common Angular modules should be imported at the base of your application.

有关 Angular 模块的更多信息,请参见 NgModules

For more information on Angular Modules, see NgModules.

更多关于 NgModule 和路由的知识

More on NgModules and routing

你可能还对下列内容感兴趣:

You may also be interested in the following: