Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ionic3 / Ngx-translate - TranslateHttpLoader with external URL

I'm loading the translation files from the server using TranslateHttpLoader in my app.module.ts like this:

export function createTranslateLoader(http: Http) {
   return new TranslateHttpLoader(http, AppConfig.API_URL+'/static/i18n/', '.json');
}

@NgModule({
  ...

  imports: [

    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: (createTranslateLoader),
        deps: [Http]
      }
    }), 

  ],
  ...
})

Everything works fine, but i'm wondering if there is a way to catch event when the loader fails to retrieve the language file for whatever reason (server issues, net con etc.) and possibly load a local json file with some default translation strings?

I want to catch this event if the app on the first load fails to grab the language file , and fallback to minimal local json file to just display translated mainetnance page/error page or something.

like image 716
mike_t Avatar asked Jul 24 '17 12:07

mike_t


2 Answers

at the end i wrote a custom loader that resolves the requirement:

import { Injectable } from '@angular/core';
import { Headers, Http, Response } from "@angular/http";
import { TranslateLoader } from '@ngx-translate/core';
import { AppConfig } from "./config"
import { Observable } from 'rxjs/Observable'; 


@Injectable()
export class CustomTranslateLoader implements TranslateLoader  {
    contentHeader = new Headers({"Content-Type": "application/json","Access-Control-Allow-Origin":"*"});

    constructor(private http: Http) {}
    getTranslation(lang: string): Observable<any>{
        var apiAddress = AppConfig.API_URL+"/static/i18n/"+ lang+".json";
        return Observable.create(observer => {
          this.http.get(apiAddress, { headers: this.contentHeader }).subscribe((res: Response) => {
                    observer.next(res.json());
                    observer.complete();               
                },
            error => {
                //  failed to retrieve from api, switch to local
                this.http.get("/assets/i18n/en.json").subscribe((res: Response) => {
                    observer.next(res.json());
                    observer.complete();               
                })
            }
            );
        }); 
    }
}

and in app.module.ts

...
import { CustomTranslateLoader } from "../services/trans-loader"
...

@NgModule({
  ...

  imports: [

    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useClass: CustomTranslateLoader,
        deps: [Http]
      }
    }), 

  ],
  ...
})
like image 121
mike_t Avatar answered Dec 28 '22 05:12

mike_t


UPDATE for Angular >= 4.3

As new Angular versions use HttpClient instead of Http, an updated and much shorter version of mike_t's CustomTranslateLoader would be:

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { TranslateLoader } from '@ngx-translate/core';
import { Observable } from 'rxjs/Observable';
import { catchError } from 'rxjs/operators';
import { AppConfig } from './config';


@Injectable()
export class CustomTranslateLoader implements TranslateLoader  {
    contentHeader = new HttpHeaders({
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': '*',
    });

    constructor(private httpClient: HttpClient) {}
    getTranslation(lang: string): Observable<any> {
        const apiAddress = AppConfig.API_URL + `/static/i18n/${lang}.json`;
        return this.httpClient.get(apiAddress, { headers: this.contentHeader })
          .pipe(
            catchError(_ => this.httpClient.get(`/assets/i18n/en.json`))
          );
    }
}


like image 42
Friedrich Avatar answered Dec 28 '22 07:12

Friedrich