如何更改角度4

时间:2018-04-14 20:59:37

标签: angular internationalization

我已经按照关于i18n https://angular.io/guide/i18n的角度教程,所以我为(messages.en.xlf和messages.fr.xlf)创建了2个文件。

当我启动我的服务器ng serve --aot --i18nFile=src/locale/messages.fr.xlf --i18nFormat=xlf --locale=fr时,我看到正确的语言。我为我的2种语言创建了2个按钮,我想根据用户的点击使用特定的messages.xlf。我怎么能这样做?

1 个答案:

答案 0 :(得分:3)

您可以配置angular i18n以从本地存储中获取语言,因此您可以在单击语言按钮时添加功能:

<button (click)='changeLang(lang)'></button>

并在ts中设置localstorage并重新加载:

changeLang(lang: string) {
   localStorage.setItem('Language', lang);
   location.reload(true);
}

在你的app forlder旁边创建一个本地文件夹并将你的翻译文件放在那里,比如messages.en.xlf,messages.fr.xlf ......

并且不要在app.module.ts

中的提供程序中添加它
export function getCurentLocale(): string {
  return localStorage.getItem('Language') || 'en';
}


providers: [
  ...
{ provide: LOCALE_ID, useValue: getCurentLocale() }
],

这是i18n-providers.ts应该是什么样的

import { LOCALE_ID, TRANSLATIONS, TRANSLATIONS_FORMAT } from '@angular/core';

 export function getTranslationProviders(): Promise<Object[]> {
    let locale = 'en';
    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 === 'en') {
    return Promise.resolve(noProviders);
  }

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

 if (locale === 'en') {
    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);
  });
   }
相关问题