From 122f858453684b3b42fa8e019df0506caa61055e Mon Sep 17 00:00:00 2001 From: Severin Date: Tue, 30 Jan 2018 09:40:49 +0100 Subject: [PATCH] Howto write a HashTranslateLoader In issue #25 @mlegenhausen pointed out a solution that shows a very common use-case for a custom TranslateLoader implementation. Maybe we can extend the readme to show this (and maybe other use-cases in the future)? Kind regards :) --- README.md | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/README.md b/README.md index 722b1ed..88abf25 100644 --- a/README.md +++ b/README.md @@ -69,3 +69,47 @@ export function HttpLoaderFactory(http: HttpClient) { ``` For now this loader only support the json format. + +## Custom TranslateLoader strategies +### HashTranslateLoader - Hashing translation files with angular-cli, webpack and SystemJS +Allow caching of translation files by the browser could help to speed up the initial load of your app but with the default setup your translation files could miss the latest changes because the cache doesn't have the latest version of your translation file yet. + +When using the angular-cli (uses webpack under the hood) you can write your own `TranslateLoader` that always loads the latest translation file available during your application build. + +```typescript +// webpack-translate-loader.ts +import { TranslateLoader } from '@ngx-translate/core'; +import { Observable } from 'rxjs/Observable'; + +export class HashTranslateLoader implements TranslateLoader { + getTranslation(lang: string): Observable { + return Observable.fromPromise(System.import(`../assets/i18n/${lang}.json`)); + } +} +``` + +When your project cannot find `System` then adding this to your `typings.d.ts` file helps: +```typescript +declare var System: System; +interface System { + import(request: string): Promise; +} +``` + +Now you can use the `HashTranslateLoader` with your `app.module`: +```typescript +@NgModule({ + bootstrap: [AppComponent], + imports: [ + TranslateModule.forRoot({ + loader: { + provide: TranslateLoader, + useClass: HashTranslateLoader + } + }) + ] +}) +export class AppModule { } +``` + +One disadvantage of this solution is that you have to rebuild your application when there are only changes inside your language files.