如何使用ngx-translate检查翻译文件是否可用于navigator.language
的结果?
我想做类似的事情:
if( checkLanguageAvailable (navigator.language)) {
this.translate.use( navigator.language );
} else {
this.translate.use( 'en' ); //Default fall back
}
答案 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
}
}