ngx-translate - 检查翻译文件是否可用

时间:2018-02-12 10:46:56

标签: javascript angular

如何使用ngx-translate检查翻译文件是否可用于navigator.language的结果?

我想做类似的事情:

if( checkLanguageAvailable (navigator.language)) {
 this.translate.use( navigator.language );
} else {
 this.translate.use( 'en' ); //Default fall back
}

2 个答案:

答案 0 :(得分:1)

您可以使用ngx-translate的getLangs()方法获取可用语言的列表:

@Component({ ... })
export class MyController {
  constructor(private translate: TranslateService) {}

  checkLanguageAvailable(lang: string): boolean {
    return this.translate.getLangs().includes(lang);
  }
}

答案 1 :(得分:0)

你可以在使用之前检查文件是否存在(make http.get,但这会加载文件......)

或使用 missingTranslationHandler ,例如: 的 app.module.ts

import ...

export function HttpLoaderFactory(httpClient: HttpClient) {
  return new TranslateHttpLoader(httpClient, 'assets/i18n/', '.json');
}

@NgModule({
  imports: [
    ...
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: (HttpLoaderFactory),
        deps: [HttpClient]
      },
      isolate: true,
      missingTranslationHandler: [{provide: MissingTranslationHandler, useClass: TranslateHandler}]
    }),
    SimpleNotificationsModule.forRoot()
  ],
...

<强> TranslateHandler

import {MissingTranslationHandler, MissingTranslationHandlerParams} from '@ngx-translate/core';

export class TranslateHandler implements MissingTranslationHandler {
  private response: String;
  handle(params: MissingTranslationHandlerParams) {   
    return 'some translated text'; // here u can return translation 
  }
}