Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular ngx-translate inside service

I am using ngx-translate and ngx-translate/http-loader for translating my ionic/angular project. I have this code inside app.module.ts imports:

TranslateModule.forRoot({
  loader: {
    provide: TranslateLoader,
    useFactory: (createTranslateLoader),
    deps: [HttpBackend]
  }
})

and this loader function in the same file:

export function createTranslateLoader(handler: HttpBackend) {
     const http = new HttpClient(handler);
     return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}

This gives me opportunity to use this kind of translation syntac inside component's html : {{ 'TEXT' | translate }} , I also can write something like that to translate inside component's ts file : var text = this.translateService.instant("TEXT");

Now I want to use translateService.instant inside service generated by command "ng generate s" I tried it but it doesn't work, it returns "TEXT" itself. So what is the problem?

like image 655
Nika Kurashvili Avatar asked May 16 '26 12:05

Nika Kurashvili


1 Answers

try this.translateService.get("TEXT").subscribe(...)

see: https://github.com/ngx-translate/core#4-use-the-service-the-pipe-or-the-directive

instant(key: string|Array, interpolateParams?: Object): string|Object: Gets the instant translated value of a key (or an array of keys). /!\ This method is synchronous and the default file loader is asynchronous. You are responsible for knowing when your translations have been loaded and it is safe to use this method. If you are not sure then you should use the get method instead.

like image 96
admir86 Avatar answered May 19 '26 03:05

admir86



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!