1

I have tried to solve my task with all of these examples in this question Angular ngx-translate usage in typescript I do not know how to connect TranslateService to my method.

Swedish translation file se.json (without key)

{
    NAME: Namn
}

English translation file en.json (without key)

{
    NAME: Name
}

typescript:

import { TranslateService } from "@ngx-translate/core";

constructor {
 private translate: TranslateService
} {
    this.translate.use(localStorage.getItem("language")); // Get selected language
}

Method that I want to translate:

setColumns(): void {
  this.loggedInUserType = Meteor.user().profile.user_type;
  if (this.type === "history") {
    this.columns = [
      { header: "NAME" },
      { header: "TOTALSUM" },
      { header: "VAT" },
      { header: "INVOICES" },
    ];
  } else if (this.type === "clients") {
    this.columns = [
      { header: "NAME" },
      { header: "ORGANIZATIONNUMBER" },
      { header: "CITY" },
      { header: "COUNTRY" },
      { header: "ACTIONS" },
   ];
    this.getClients();
  }
}

1 Answers1

0
  1. app.module.ts

    export function HttpLoaderFactory(httpClient: HttpClient) {
      return new TranslateHttpLoader(httpClient, 'assets/i18n/', '.json');
    }
    
    export class TranslateHandler implements MissingTranslationHandler {
      handle(params: MissingTranslationHandlerParams) {
        /* some logic */
      }
    }
    
    export function appInitializerFactory(translateService: TranslateService, injector: Injector): () => Promise<any> {
      // tslint:disable-next-line:no-any
      return () => new Promise<any>((resolve: any) => {
        const locationInitialized = injector.get(LOCATION_INITIALIZED, Promise.resolve(null));
        locationInitialized.then(() => {
          translateService.use(localStorage.getItem("language") || window.navigator.language) // here u can change language loaded before reander enything
            .pipe(take(1))
            .subscribe(() => {},
            err => console.error(err), () => resolve(null));
        });
      });
    }
    
    @NgModule({
        imports: [
            ...,
            TranslateModule.forRoot({
                loader: {
                    provide: TranslateLoader,
                    useFactory: (HttpLoaderFactory),
                    deps: [HttpClient]
                },
                isolate: false,
                missingTranslationHandler: [{provide: MissingTranslationHandler, useClass: TranslateHandler}]
            }),
        ]
        providers: [
            ...,
            {
                provide: APP_INITIALIZER,
                useFactory: appInitializerFactory,
                deps: [TranslateService, Injector],
                multi: true
            }
        ]
    })
    export class AppModule {}
    
  2. in module of your component add TranslationModule

  3. in component constructor public ts: TranslateService) {}

  4. now u can use:

    this.ts.instant('YOUR_KEY'); // return translated string or your key if translation not founded, but u can change logic in TranslateHandler
    
  5. all translations stored in assets/i18n/. for example en.json

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574