问题描述
我正在我的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]
}
}),
],
...
})
一切正常,但是我想知道当加载器由于某种原因(服务器问题,网络con等)无法检索语言文件并且可能加载带有一些默认翻译字符串的本地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文件,只显示翻译的mainetnance页面/错误页面或其他内容,我想要捕获此事件。
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.
推荐答案
最后我写了一个解决这个要求的自定义加载器:
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();
})
}
);
});
}
}
和app.module.ts
and in app.module.ts
...
import { CustomTranslateLoader } from "../services/trans-loader"
...
@NgModule({
...
imports: [
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useClass: CustomTranslateLoader,
deps: [Http]
}
}),
],
...
})
这篇关于Ionic3 / Ngx-translate - 带外部URL的TranslateHttpLoader的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!