Angular 2 Keep ng2-translate DRY when using multiple modules

395 views Asked by At

I am new working with Angular 2 and have a question regarding keeping the code DRY when using multiple modules.

I have a shared module where i import and export common used functionality for other modules.

One of those imports are ng2-translate.

But when I import the SharedModule into a new module, I will need to import and configure the TranslateModule from ng2-translate again, to be able to configure it.

This gives me a pattern i don't like if i should work with multiple modules.

So how would I keep this code DRY and maintain the best practices?

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { TranslateModule } from 'ng2-translate';

@NgModule({
  imports: [
    CommonModule,
    TranslateModule
  ],
  exports: [
    CommonModule,
    TranslateModule
  ]
})

export class SharedModule {
}

AppModule

import { NgModule } from '@angular/core';
import { HttpModule, Http } from '@angular/http';
import { TranslateModule, TranslateLoader, TranslateStaticLoader, TranslateService } from 'ng2-translate';
import { SharedModule } from './shared/shared.module';
import { AppComponent } from './app.component';

export function translateLoaderFactory(http: Http) {
  return new TranslateStaticLoader(http, '../assets/i18n', '.json')
}

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    HttpModule,
    TranslateModule.forRoot({
      provide: TranslateLoader,
      useFactory: translateLoaderFactory,
      deps: [Http]
    }),
    SharedModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {
  constructor(translateService: TranslateService) {

    translateService.setDefaultLang('en-US');

    translateService.use('sv-SE');
  }
}

This is my basic structure, if I add a new module I will have to import the SharedModule, TranslateModule and setting the default language using the TranslateService all over again.

How do I prevent this pattern?

0

There are 0 answers