共计 1555 个字符,预计需要花费 4 分钟才能阅读完成。
每个 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 中注册的提供程序在整个应用程序中都可用的起因。