Ionic3/Ngx-translate - 带有外部 URL 的 TranslateHttpLoader [英] Ionic3 / Ngx-translate - TranslateHttpLoader with external URL
问题描述
我正在使用我的 app.module.ts 中的 TranslateHttpLoader 从服务器加载翻译文件,如下所示:
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]
}
}),
],
...
})
一切正常,但我想知道是否有办法在加载程序因任何原因(服务器问题、网络配置等)未能检索语言文件时捕获事件,并可能加载带有一些的本地 json 文件默认翻译字符串?
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?
如果第一次加载的应用程序无法获取语言文件,我想捕获此事件,并回退到最小的本地 json 文件以仅显示翻译的维护页面/错误页面或其他内容.
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.
推荐答案
UPDATE for Angular >= 4.3
由于新的 Angular 版本使用 HttpClient
而不是 Http
,这是 mike_t 的 CustomTranslateLoader
将是:
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`))
);
}
}
这篇关于Ionic3/Ngx-translate - 带有外部 URL 的 TranslateHttpLoader的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!