core
core copied to clipboard
Translate service doesn't work within other service
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.
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.
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
any updates?