diff --git a/packages/core/language/src/shared/language.provider.ts b/packages/core/language/src/shared/language.provider.ts index 735faa27a..4c790963c 100644 --- a/packages/core/language/src/shared/language.provider.ts +++ b/packages/core/language/src/shared/language.provider.ts @@ -29,9 +29,14 @@ const TIMEOUT_DURATION = 5000; /** * Make sure you only call this method in the root module of your application, most of the time called AppModule. */ -export function provideTranslation(loader?: Provider): EnvironmentProviders { +export function provideTranslation( + defaultLanguage?: string | undefined, + loader?: Provider +): EnvironmentProviders { return makeEnvironmentProviders([ - importProvidersFrom(TranslateModule.forRoot(setTranslationConfig(loader))), + importProvidersFrom( + TranslateModule.forRoot(setTranslationConfig(loader, defaultLanguage)) + ), { provide: APP_INITIALIZER, useFactory: (languageService: LanguageService) => () => { @@ -53,9 +58,10 @@ export function provideTranslation(loader?: Provider): EnvironmentProviders { } export const setTranslationConfig = ( - loader?: Provider + loader?: Provider, + defaultLanguage?: string ): TranslateModuleConfig => ({ - defaultLanguage: 'fr', + defaultLanguage: defaultLanguage, loader: loader ?? DEFAULT_LANGUAGE_LOADER, missingTranslationHandler: { provide: MissingTranslationHandler, diff --git a/packages/core/language/src/shared/language.service.ts b/packages/core/language/src/shared/language.service.ts index e7d710d01..88abcef4d 100644 --- a/packages/core/language/src/shared/language.service.ts +++ b/packages/core/language/src/shared/language.service.ts @@ -11,6 +11,14 @@ export class LanguageService { readonly language$ = new BehaviorSubject(undefined); constructor(public translate: TranslateService) { + if ( + !this.translate.defaultLang || + !this.matchLanguage(this.translate.defaultLang) + ) { + this.setBrowserLanguage(); + } + } + private setBrowserLanguage() { this.language = this.translate.getBrowserLang(); const lang = this.getLanguage(); this.translate.setDefaultLang(lang); @@ -18,11 +26,15 @@ export class LanguageService { } public getLanguage(): string { - return this.language.match(/en|fr/) ? this.language : 'en'; + return this.matchLanguage(this.language) ? this.language : 'en'; + } + + private matchLanguage(lang: string): boolean { + return !!lang.match(/en|fr/); } public setLanguage(language: string) { - this.language = language.match(/en|fr/) ? language : 'en'; + this.language = this.matchLanguage(language) ? language : 'en'; combineLatest([ this.translate.use(this.language), this.translate.reloadLang(this.language)