You can load multiple keys at the same time with the service, you will receive an array of values
any examples ?
translate.get(['key1', 'key2']).subscribe((res: string[]) => {
console.log(res);
});
it also work with translate.instant() which is synchronous (but only works when the language has been loaded)
... and one way to ensure that the translations are loaded is including them in the bundle, e.g. with webpack:
translateService.setTranslation("en", require("../i18n/locale-en.json"));
translateService.setTranslation("de", require("../i18n/locale-de.json"));
Obviously you shouldn't do this if you support dozens of languages, but for few languages the impact on bundle size is often negligible.
@bedag-moo, thank you for providing this valuable information. After reading your comment I saw that this is mentioned in the documentation, but the concrete example uses hardcoding of the translations as a JavaScript object. @ocombe, I think bedag-moo's example should be added alongside the current one, since it depicts a more "real-world" scenario.
In my case I currently support only two languages and I've been looking for a way to include the translations directly into the bundle. Not only this saved me 2 HTTP requests (with the possibility of them failing on flacky connections), but also removed the text flickering caused by loading the translations on the fly.
@bedag-moo hey man where do I put this ? In the AppComponent right? Also do I still need to import the TranslateModule as so :
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: (createTranslateLoader),
deps: [Http]
}
}),
@mp3por, this configuration works for me:
// app.component.ts
ngOnInit() {
this.translate.setTranslation('en', require('./../assets/i18n/en.json'));
// add other languages here
}
// app.module.ts
import { TranslateModule } from '@ngx-translate/core';
@NgModule({
imports: [
// other modules
TranslateModule.forRoot()
],
declarations: [AppComponent],
bootstrap: [AppComponent]
})
export class AppModule { }
It seems that there is no need for the createTranslateLoader factory.
Yes, it's optional if you prefer to set the translations yourself.
@tsvetan-ganev you can do a PR to update the docs if you want :)
Most helpful comment
... and one way to ensure that the translations are loaded is including them in the bundle, e.g. with webpack:
Obviously you shouldn't do this if you support dozens of languages, but for few languages the impact on bundle size is often negligible.