关于 Angular 应用 Module 的 forRoot 方法的讨论

JerryWang_汪子熙 -
关于 Angular 应用 Module 的 forRoot 方法的讨论

在 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中的提供商在整个应用中都是可用的。

特别申明:本文内容来源网络,版权归原作者所有,如有侵权请立即与我们联系(cy198701067573@163.com),我们将及时处理。

Tags 标签

angularjavascript前端html5html

扩展阅读

加个好友,技术交流

1628738909466805.jpg