core
core copied to clipboard
TranslateService.use with multiple calls causes to display the wrong language
Current behavior
Changing the language multiple times in a short amount of time e.g. from the default language to a language which hasn't been loaded yet and then back to the default language ("en"
-> "de"
-> "en"
) with the TranslateService.use(...)
function causes the not yet loaded language ("de"
) to still being used for texts instead of the last used language "en"
(e.g. it's still "Hallo Welt"
instead of "Hello World"
).
We have encountered this problem because we have multiple sources where the language is set from (default langauge, browser language and from a user config saved/pulled from a server).
Expected behavior
The last used language should be used in the texts ("Hello World"
instead of "Hallo Welt"
)
How do you think that we should fix this?
Stop the loading of the language when a new language is being set while loading
Minimal reproduction of the problem with instructions
Use 2 translations (one as the default and another language which isn't loaded yet). Then create the following service:
@Injectable({
providedIn: "root",
})
export class SomeService {
constructor(
private translate: TranslateService,
) {
this.translate.addLangs(["en", "de"]); // this is is normally a reference to a list of all our supported languages (generated dynamically)
setTimeout(() => {
this.translate.use("de"); // this language has not been loaded yet
console.log(this.translate.currentLang); // "de"
this.translate.use("en"); // default language
console.log(this.translate.currentLang); // "en" - but all texts are still in "de"
}, 10000); // wait a bit before testing
}
}
My app.module.ts
config for ngx-translate/core:
...
export function httpLoaderFactory(http: HttpBackend) {
return new MultiTranslateHttpLoader(http, ["./assets/common/i18n/", "./assets/i18n/"]);
}
@NgModule({
...
imports: [
...
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: httpLoaderFactory,
deps: [HttpBackend],
},
compiler: {
provide: TranslateCompiler,
useClass: TranslateMessageFormatCompiler,
},
defaultLanguage: "en",
}),
...
],
...
})
...
Environment
ngx-translate version: 15.0.0
Angular version: 17.3.5 and 16.2.14
Browser:
- [x] Chrome (desktop) version 124.0.6367.119
- [ ] Chrome (Android) version XX
- [ ] Chrome (iOS) version XX
- [x] Firefox version 115.9.1esr
- [ ] Safari (desktop) version XX
- [ ] Safari (iOS) version XX
- [ ] IE version XX
- [x] Edge version 124.0.2478.67
For Tooling issues:
- Node version: v20.12.2
- Platform: Windows
Others: Windows 10 22H2, Visual Studio Code, NPM