Skip to content

Commit

Permalink
fix(core): language add ability to define the default language
Browse files Browse the repository at this point in the history
fix(core): language use the browser language only if the default is not set
  • Loading branch information
alecarn committed Nov 12, 2024
1 parent 9bf8df6 commit aaf16c9
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
14 changes: 10 additions & 4 deletions packages/core/language/src/shared/language.provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) => () => {
Expand All @@ -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,
Expand Down
16 changes: 14 additions & 2 deletions packages/core/language/src/shared/language.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,30 @@ export class LanguageService {
readonly language$ = new BehaviorSubject<string>(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);
this.language$.next(lang);
}

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)
Expand Down

0 comments on commit aaf16c9

Please sign in to comment.