likes
comments
collection
share

从 RouterModule.forRoot 方法说起

作者站长头像
站长
· 阅读数 309

每个 Angular 开发人员在学习路由设计时,都遇到过如下的代码:

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

const routes: Routes = [
    { path: '',   redirectTo: '/index', pathMatch: 'full' }
];

@NgModule({
  imports: [
    RouterModule.forRoot(routes)
  ],
  ...
})
export class AppModule { }

这个约定也用在 ngx-bootstrap 和 Angular Material 中。其命名约定意味着,在调用 forRoot() 方法时,必须向应用程序的根 NgModule 注册给定模块。 那为什么它需要在应用程序的根 module 中调用,而不是任何其他 NgModule?

首先,forRoot() 约定返回什么数据类型? 通常,此方法的返回类型是符合 ModuleWithProviders 接口的对象。 这个接口是一个被接受的 NgModule import 并且有两个属性:

interface ModuleWithProviders { 
  ngModule: Type<any>
  providers: Provider[]
}

简而言之,forRoot() 方法返回一个 NgModule 及其提供者依赖项。 这与根 NgModule 有什么关系? 事实上,虽然这个约定暗示着它应用在应用程序的根目录中导入,但在许多情况下,我们可以在非根 NgModule 中导入它,同样会起作用。

下面是一个例子,ngx-bootstrap 中的 ModalModule 使用 forRoot() 约定的方式:

import { NgModule, ModuleWithProviders } from '@angular/core';

import { ModalBackdropComponent } from './modal-backdrop.component';
import { ModalDirective } from './modal.component';
import { PositioningService } from '../positioning';
import { ComponentLoaderFactory } from '../component-loader';

@NgModule({
  declarations: [ModalBackdropComponent, ModalDirective],
  exports: [ModalBackdropComponent, ModalDirective],
  entryComponents: [ModalBackdropComponent]
})
export class ModalModule {
  public static forRoot(): ModuleWithProviders {
    return {ngModule: ModalModule, providers: [ComponentLoaderFactory, PositioningService]};
  }
}

注意: ModalModule 没有在 @NgModule 装饰器中声明任何提供者,而是在静态 forRoot() 方法中声明。

尽管调用 forRoot() 方法理论上可以在子 NgModules 中工作,但在应用程序的根 module 中调用 forRoot,能带来如下收益。当使用 @Injectable 装饰一个类并在 NgModule 中注册为提供者时,这个类被唯一创建一次,并且一个实例在整个应用程序中共享。 当 Angular 引导根 NgModule 时,所有 NgModule 中的所有可用导入,都会在那时注册并可供整个应用程序使用——它们是全局的。 这就是为什么在子 NgModule 中注册的提供程序在整个应用程序中都可用的原因。