Created
January 20, 2020 10:28
-
-
Save kristofdegrave/64863e249bbc8768fe33fc666dfa8bf5 to your computer and use it in GitHub Desktop.
Loading additional translations when a lazy loaded module get's loaded
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Observable } from 'rxjs'; | |
import { tap, refCount, publishReplay, map } from 'rxjs/operators'; | |
import { | |
MissingTranslationHandler, | |
MissingTranslationHandlerParams | |
} from '@ngx-translate/core'; | |
export class LazyModuleMissingTranslationHandler extends MissingTranslationHandler { | |
translationsLoaded: { [language: string]: Observable<any> | boolean } = {}; | |
handle(params: MissingTranslationHandlerParams) { | |
const key = params.key; | |
const currentLang = | |
params.translateService.currentLang || | |
params.translateService.defaultLang; | |
const translateLoader = params.translateService.currentLoader; | |
if (!currentLang) { | |
return; | |
} | |
const status = this.translationsLoaded[currentLang]; | |
if (typeof status === 'undefined') { | |
// load translations for language | |
// when done set translationsLoaded[currentLang] to true | |
const $translations = translateLoader.getTranslation(currentLang).pipe( | |
tap(translations => | |
params.translateService.setTranslation( | |
currentLang, | |
translations, | |
true | |
) | |
), | |
tap(() => (this.translationsLoaded[currentLang] = true)), | |
publishReplay(), | |
refCount() | |
); | |
// translations are being loaded, put observable in translationsLoaded[currentLang] | |
this.translationsLoaded[currentLang] = $translations; | |
// return observable for requested translation | |
return $translations.pipe( | |
map(translations => | |
params.translateService.getParsedResult( | |
translations, | |
key, | |
params.interpolateParams | |
) | |
) | |
); | |
} else { | |
if (typeof status !== 'boolean') { | |
// translations are being loaded, return observable for requested translation | |
return status.pipe( | |
map(translations => | |
params.translateService.getParsedResult( | |
translations, | |
key, | |
params.interpolateParams | |
) | |
) | |
); | |
} | |
} | |
return; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment