1

In our Angular App we have Feature Modules as well as Core and Shared Module as described by the Angular - linkStyle Structure best practices.

We use ng2-translate and as per doc, we should call forRoot() in App Module (root module).

This is how our App Module looks like:

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    FeatureAModule,
    FeatureBModule,
    CoreModule,
    TranslateModule.forRoot({
        provide: TranslateLoader,
        useFactory: (createTranslateLoader),
        deps: [Http]
    })
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

As we want to translate our menu and it's part of the Core Module we had to import the Translate Module there, like so:

@NgModule({
  imports: [
    TranslateModule
  ],
  exports: [
      FormsModule,
      MenuComponent,
      BreadcrumbComponent
  ],
  declarations: [MenuComponent, BreadcrumbComponent]
})
export class CoreModule {
    constructor( @Optional() @SkipSelf() parentModule: CoreModule) {
      throwIfAlreadyLoaded(parentModule, "CoreModule");
    }
 }

Does this make sense? Should I remove TranslateModule.forRoot(...) from the App Module and place it in the imports of the Core Module ? Is that wrong?

4

1 回答 1

3

如果您正在关注文档,那么AppModule将是唯一要导入的文档CoreModuleTranslateModule.forRoot()如果是这样的话,如果你简单地添加到CoreModule.imports数组和数组TranslateModule中,事情就会很好地工作CoreModule.exports。然后在您的 中AppModule,您需要做的就是导入 ,CoreModule而无需再次处理翻译模块。

这类似于文档建议如何集成RouterModule例如。看看这个。请注意,它RouterModule.forRoot()是在 中导入的AppRoutingModule,而不是在AppModule其自身中导入的。所以在你的地方,我会:

核心模块

// forRoot is OK here because AppModule is the only one to import CoreModule
imports: [TranslateModule.forRoot(...)]

// will make Translate available to AppModule
exports: [TranslateModule]

应用模块

//importing Core will import Translate and its services provided by .forRoot()
imports: [CoreModule]

共享模块

//only if the components, directives and pipes of SharedModule need Translate
imports: [TranslateModule]

//so that all modules that import SharedModule will have Translate access
exports: [TranslateModule]
于 2017-06-24T16:08:23.677 回答