core icon indicating copy to clipboard operation
core copied to clipboard

Translate service doesn't work within other service

Open vahidvdn opened this issue 5 years ago • 3 comments

In my components (lazy loaded routes) When I set the following, it works fine:

constructor( public translate:TranslateService ) {
    this.translate.setDefaultLang( this.langService.lang );
    this.translate.use( this.langService.lang );
}

I have my own LangService just to save user's selected language across the application. I set it to lang property and use TranslateService there:

lang:string = "fa";

constructor(public translate: TranslateService) {

	// this works
	console.log(this.lang);

	// this doesn't work
	this.translate.setDefaultLang( this.lang );
    this.translate.use( this.lang );

}

Now I simply inject LangService to my component, but the translation doesn't work. Any idea?

Note: I imported TranslateModule into a SharedModule, and import that SharedModule in my other lazy loaded modules.

vahidvdn avatar May 08 '19 06:05 vahidvdn

This answer is a bit late, but it's my understanding that services are singletons when injected using the DI system. This means your constructor code is only getting run once when the service is first initialized, and not when it is injected into your other components.

pomo-keith avatar Jun 11 '19 13:06 pomo-keith

I do the same - call forRoot in my main module and imported TranslateModule into a SharedModule, and then import that SharedModule in my other lazy loaded modules.
And I have the same issue. I have found when you inject TranslateService in lazy-loaded module it creates a new instance of TranslateService with standalone store - and that store is empty.

I got it ). https://github.com/ngx-translate/core#lazy-loaded-modules I added to my lazy-loaded module TranslateModule.forChild(translateConfig) even I have imported in that module SharedModule before - and translations are working now correctly

uaKorona avatar Jul 25 '19 11:07 uaKorona

any updates?

saver711 avatar Aug 29 '23 14:08 saver711