'Angular translation service subscription in lazy loaded module
I have imported TranslateModule in app.module.ts:
export function createTranslateLoader(http: HttpClient) {
return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}
imports: [...
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: createTranslateLoader,
deps: [HttpClient],
},
}),
]
And then in the app.component.ts:
ngOnInit(): void {
this.translateService.setDefaultLang('sl');
this.translateService.addLangs(['en', 'sl', 'hr']);
this.selectedLanguage = localStorage.getItem(AppSettings.LS_LANGUAGE)!;
if (!this.selectedLanguage) this.setLanguage('sl');
else this.applyLanguage();
}
I change the language with the setLanguage function
public setLanguage(lang: string): void {
localStorage.setItem(AppSettings.LS_LANGUAGE, lang);
this.selectedLanguage = lang;
this.applyLanguage();
}
private applyLanguage() {
this.translateService.use(this.selectedLanguage);
}
In the lazy loaded module, I import the TranslateModule as such:
imports: [..., TranslateModule.forChild()]
But when I subscribe to a translation in the lazy loaded module, it only translates it initially, but doesn't update, when I change the language:
this.translateService
.get('...')
.subscribe((translation) => console.log(translation));
If I move the function above, to app.module.ts, it works fine, but once I move it to the lazy loaded module, it no longer works.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
