【问题标题】:How to change locale in angular 4如何在 Angular 4 中更改语言环境
【发布时间】:2018-04-14 20:59:37
【问题描述】:

我已经按照关于 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。我该怎么做?

【问题讨论】:

    标签: angular internationalization


    【解决方案1】:

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

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

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

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

    在您的应用程序文件夹旁边创建一个本地文件夹并将您的翻译文件放在那里,例如 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);
      });
       }
    

    【讨论】:

    • 谢谢你的回答。我理解逻辑,但由于我是 Angular 新手,我不知道在哪里提供这段代码。它在我的 app.component.ts 中吗?还是我必须创建一个 i18n-providers.ts 文件?
    • 如果您没有,请在您的应用文件夹中创建它
    • 我必须在某处声明或导入它吗?还是会自动完成?
    • 不客气,我更新了我的答案,不要忘记 app.module.ts 中的配置,检查我的更新
    • 为什么不用 httpClient 而不是 xhr?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多