如何在Angular I18n

时间:2018-05-07 18:41:33

标签: angular internationalization angular-i18n

基于此处的原始文档https://angular.io/guide/i18n。 src / app / app.component.html只有英文文本。 messages.fr.xlf是具有法语文本的文件,但它是自动生成的,不建议触摸它。

如果我想使用法语文本而不是英语呈现app.component.html,我会在哪里指定法语消息“Bonjour”等?

1 个答案:

答案 0 :(得分:0)

你必须在你的i18n-providers.ts中设置你的默认语言,这里有一个例子,如果你的默认语言是法语(fr),你可以给它一个默认的翻译文件messages.xlf和

 ./locale/messages.${locale}.xlf 

对于其他语言,请记住,如果使用aot

构建,i18n将无法工作
  import { TRANSLATIONS, TRANSLATIONS_FORMAT, LOCALE_ID } from '@angular/core';

 export function getTranslationProviders(): Promise<Object[]> {
 let locale = 'fr'; //set it here
 if (localStorage.getItem('Language') !== undefined) {
     locale = localStorage.getItem('Language');
 }

 // return no providers if fail to get translation file for locale
 const noProviders: Object[] = [];

 // No locale or U.S. English: no translation providers
 if (!locale || locale === 'fr') {
     return Promise.resolve(noProviders);
 }

 let translationFile = `./locale/messages.${locale}.xlf`;

 if (locale === 'fr') {
    translationFile = './messages.xlf';
 }

 return loadTranslationFile(translationFile)
    .then( (translations: string ) => [
        { provide: TRANSLATIONS, useValue: translations },
        { provide: TRANSLATIONS_FORMAT, useValue: 'xlf' },
        { provide: LOCALE_ID, useValue: locale }
    ])
    .catch(() => noProviders); // ignore if file not found
 }

 function loadTranslationFile(file) {
  return new Promise(function (resolve, reject) {
    const   xhr: XMLHttpRequest = new XMLHttpRequest();
    xhr.open('GET', file, false);
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            if (xhr.status === 200 || xhr.status === 0) {
                resolve(xhr.responseText);
            } else {
                reject({
                    status: xhr.status,
                    statusText: xhr.statusText
                });
            }
        } else {
            reject({
                status: xhr.status,
                statusText: xhr.statusText
            });                }
    };
    xhr.onerror = function () {
        reject({
            status: xhr.status,
            statusText: xhr.statusText
        });
    };
    xhr.send(null);
 });
}