From 3f598779a5066434bd8f75a1c70bae8eb1816471 Mon Sep 17 00:00:00 2001 From: Severin Date: Fri, 16 Mar 2018 14:36:21 +0100 Subject: [PATCH] docs(README): how to write a HashTranslateLoader * 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 :) * Updated to review --- README.md | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/README.md b/README.md index 722b1ed..a75b78d 100644 --- a/README.md +++ b/README.md @@ -69,3 +69,44 @@ export function HttpLoaderFactory(http: HttpClient) { ``` For now this loader only support the json format. + +## Angular CLI/Webpack TranslateLoader Example +If you are using 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 WebpackTranslateLoader implements TranslateLoader { + getTranslation(lang: string): Observable { + return Observable.fromPromise(System.import(`../assets/i18n/${lang}.json`)); + } +} +``` + +Cause `System` will not be available you need to add it to your custom `typings.d.ts`: +```typescript +declare var System: System; +interface System { + import(request: string): Promise; +} +``` + +Now you can use the `WebpackTranslateLoader` with your `app.module`: +```typescript +@NgModule({ + bootstrap: [AppComponent], + imports: [ + TranslateModule.forRoot({ + loader: { + provide: TranslateLoader, + useClass: WebpackTranslateLoader + } + }) + ] +}) +export class AppModule { } +``` + +The disadvantage of this solution is that you have to rebuild the application everytime your translate files has changes.