Ionic3 / Ngx-translate - 带外部URL的TranslateHttpLoader

时间:2017-07-24 12:40:31

标签: ionic3 ngx-translate

我在我的app.module.ts中使用TranslateHttpLoader从服务器加载翻译文件,如下所示:

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]
      }
    }), 

  ],
  ...
})

一切正常,但我想知道当加载程序由于某种原因(服务器问题,网络con等)无法检索语言文件并且可能加载本地json文件时是否有办法捕获事件有一些默认的翻译字符串?

如果第一次加载的应用程序无法获取语言文件,并且回退到最小的本地json文件,只显示已翻译的mainetnance页面/错误页面或其他内容,我想要捕获此事件。

2 个答案:

答案 0 :(得分:2)

最后我写了一个解决了这个要求的自定义加载器:

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();               
                })
            }
            );
        }); 
    }
}

和app.module.ts

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

@NgModule({
  ...

  imports: [

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

  ],
  ...
})

答案 1 :(得分:1)

更新为Angular> = 4.3

由于新的Angular版本使用HttpClient而不是Http,因此mike_t's CustomTranslateLoader的更新版本和更短版本是:

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`))
          );
    }
}