3

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?

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

If I understand correct then in your newly generated service you have to simply inject the translate service:

constructor(translateService: TranslateService) {} 

2 Comments

Yes I do that, but I thing configuration that I write inside app.module.ts doesn't work for service but only components
Here are a detailed description about Translate service. Maybe this will help you. codeandweb.com/babeledit/tutorials/…
0

First inject the translate service in your service constructor:

constructor(public translateService: TranslateService) {} 

And then use it to get the translation from current language:

this.translateService.getTranslation(this.translateService.currentLang).subscribe((translation: string) => { this.translationText= translation.text; }); 

Comments

0

I had the same issue, but i add to the constructor of the service generated by the command the language and fix it to me.

constructor( private translate: TranslateService, ) { this.translate.use(environment.lang); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.