首页 文章

Angular 2应用程序结构/核心模块和第三方库

提问于
浏览
4

我试图找到一个很好的方法来构建我的Angular 2应用程序 . Angular 2样式指南建议创建核心模块 . 如果我理解正确,核心模块的目标是收集一次性使用的类和组件,并保持根模块的纤薄 . 还写了我应该将资产所需的所有模块导入核心模块 .

对于需要包含在Method forRoot()中的第三方库(如NgBootstrap或angular2-notifications),我有点困惑 . 通常,只应在根模块中调用forRoot()方法 . 我应该在根模块或核心模块中包含这些模块吗?

在以下示例中,我需要为angular2-notifications进行一些配置 . 为了保持我的根模块的纤薄,我在核心模块中导入了SimpleNotifications .

  • 这是正确的方法吗?为了使应用程序正常工作,我仍然需要在App Module中导入SimpleNotificationsModule.forRoot() .

  • 为什么我需要在核心模块中再次导入SimpleNotificationsModule . 不应该由app模块提供 . 我认为,由于forRoot(),他们的核心模块使用与其他模块相同的导入模块?

  • 如果是,我应该在核心模块中导入SimpleNotifications吗?我真的应该在那里调用forRoot()方法吗?


应用模块

...
import {SimpleNotificationsModule} from 'angular2-notifications';

@NgModule({
    declarations: [...],
    imports: [
     BrowserModule,
     CoreModule,
     NgbModule.forRoot(),
     SimpleNotificationsModule.forRoot(),
    ],
    bootstrap: [AppComponent]
})
export class AppModule {}

应用组件

...
<notifications></notifications>

核心模块

import {SimpleNotificationsModule} from 'angular2-notifications';
import {NotificationsComponent} from 
'./notifications/notifications.component';

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    HttpModule,
    RouterModule,
    SimpleNotificationsModule
 ],
  declarations: [...],
  exports: [NotificationsComponent]
})
export class CoreModule {
  constructor(@Optional() @SkipSelf() parentModule: CoreModule) {
    throwIfAlreadyLoaded(parentModule, 'core module');
 }
}

NotificationsComponent

import {Component, ViewEncapsulation} from '@angular/core';

@Component({
   selector: 'notifications',
   template: `<simple-notifications [options]="notificationOptions">
   </simple-notifications>`,
   styleUrls: ['./notifications.component.css'],
   encapsulation: ViewEncapsulation.None
})
export class NotificationsComponent {

  public notificationOptions = {
    position: ['top', 'right'],
    timeOut: 5000,
    maxStack: 5,
    lastOnBottom: true
  };
}

1 回答

  • 1

    当我们想要从模块注册服务提供者时,使用.forRoot() .

    • 如果需要从模块引用组件/指令或模型,则不使用forRoot()导入模块 . 对应用程序中导入模块的时间没有限制 .

    • 如果需要从模块提供服务,请使用forRoot()导入模块 . 通常,我们以这种方式导入模块只使用服务作为单例 .

    总之,forRoot()约定表示使用ModuleWithProviders接口导入NgModule及其提供程序的方法 . NgModule forRoot()惯例

    核心模块通常也用于故事单例(如身份验证服务,日志记录,通知服务)和仅使用一次的组件(应用程序 Headers ,导航栏,通知栏) . 此模块仅将一个导入到应用程序的根目录 .

    现在你的问题:

    在Core模块中简单导入SimpleNotificationsModule.forRoot(),并确保在App模块中导入Core模块 . 无需将SimpleNotificationsModule导入App模块 . 此外,您可以从App模块中删除NgbModule.forRoot()并将其放入Core模块导入中 .

    如果您有功能模块(如UserManagementModule),则可以导入SimpleNotificationsModule(不带.forRoot()),并且您将获得通知组件的所有引用,而无需创建第二个通知服务实例 .

相关问题