我试图找到一种构建 Angular 2 应用程序的好方法。 Angular 2 风格指南推荐创建一个核心模块。如果我理解正确的话,核心模块的目标是收集一次性类和组件并保持根模块的 slim 。还写了我应该将 Assets 所需的所有模块导入核心模块。
对于需要包含在方法 forRoot() 中的第三方库(如 NgBootstrap 或 angular2-notifications),我有点困惑。通常只应在根模块中调用 forRoot() 方法。我应该将此类模块包含在根模块中还是核心模块中?
在下面的示例中,我需要为 angular2-notifications 做一些配置。为了让我的根模块保持 slim ,我在核心模块中导入了 SimpleNotifications。
- 这是正确的方法吗?为了使该应用正常运行,我仍然需要在应用模块中导入 SimpleNotificationsModule.forRoot()。
- 为什么我需要在核心模块中再次导入 SimpleNotificationsModule。它不应该由应用程序模块提供吗?我认为多亏了 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');
}
}
通知组件
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
};
}
最佳答案
.forRoot() 当我们想为模块中的服务注册提供者时使用。
- 如果需要引用,导入不带forRoot()的模块 模块中的组件/指令或模型。在应用程序中导入模块的次数没有限制。
- 如果您需要从模块提供服务,请使用 forRoot() 导入模块。通常,我们仅以这种方式导入模块以将服务用作单例。
In summary, the forRoot() convention represents a way to import an NgModule along with its providers using the ModuleWithProviders interface. The NgModule forRoot() Convention
核心模块通常也用于故事单例(如身份验证服务、日志记录、通知服务)和只使用一次的组件(应用程序标题、导航栏、通知栏)。此模块仅将 ones 导入到应用程序的根目录。
现在你的问题:
在您的核心模块中简单地导入 SimpleNotificationsModule.forRoot() ,并确保您在 App 模块中导入核心模块。无需将 SimpleNotificationsModule 导入 App 模块。此外,您可以从 App 模块中删除 NgbModule.forRoot() 并将其放入核心模块导入中。
如果您有功能模块(如 UserManagementModule),那么您可以导入 SimpleNotificationsModule(无需 .forRoot()),您将拥有通知组件的所有引用,而无需创建通知服务的第二个实例。
关于Angular 2 应用程序结构/核心模块和第三方库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43919632/