在 Angular 开发中,咱们常常遇到一个 NgModule 在导入时须要调用它的动态 forRoot 办法。,最值得注意的例子是 RouterModule. 当在 Angular 利用的根目录注册这个模块时,导入RouterModule的形式如下:
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 中。这个办法有什么特别之处,以至于它须要在应用程序的根目录调用,而不是在其余NgModule中调用?
对于初学者来说,forRoot() 约定返回什么?通常,这个办法的返回类型是一个合乎ModuleWithProviders
接口的对象
。这个接口是一个可承受的NgModule导入接口,它有两个属性:
interface ModuleWithProviders { ngModule: Type<any> providers: Provider[]}
forRoot() 办法会返回一个 NgModule 及其依赖的提供商。这和根 NgModule 有什么关系?兴许什么都没有。事实上,只管这种约定意味着它必须在利用的根模块处导入,但在很多状况下,你能够在非根模块中导入它,它也能工作。
上面是 ModalModule 在ngx-bootstrap中应用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]}; }}
只管从实践上讲,导入forRoot()办法的额定提供程序。在子ngmodule中是可行的,但将它注册到应用程序的根目录,在很多方面都有帮忙。
首先,思考 providers 的注入形式与组件和指令有何不同。通常,当用@Injectable装璜一个类并在NgModule中注册为提供商时,这个类只创立一次,并且这个实例会在整个利用中共享。当Angular疏导根模块时,所有NgModule中所有可用的导入都会在那时注册,并对整个利用都可用——它们是全局的。这就是为什么注册在子NgModule中的提供商在整个利用中都是可用的。