首页 > 解决方案 > 使用 ember-intl 异步加载翻译

问题描述

我正在尝试实现翻译的异步获取。publicOnly我按照文档的说法设置了true

// config/ember-intl.js
module.exports = function() {
  return {
    publicOnly: true
  }
};

跳过设置locales密钥的步骤,因为翻译存储在/translations文件夹中。

接下来,我应该修改beforeModel钩子以异步获取翻译,这就是文档非常模糊的地方:

// app/routes/application.js
export default Ember.Route.extend({
  intl: Ember.inject.service(),
  async beforeModel() {
    let translations = await fetch('/api/translations.json');
    this.get('intl').addTranslations('en-us', translations);
    this.get('intl').setLocale('en-us');
  }
});

这些行应该如何工作:

let translations = await fetch('/api/translations.json');
this.get('intl').addTranslations('en-us', translations);

translations.json在运行时,我在文件夹中的任何地方都没有文件dist。我dist/translations/en-us.json只有我唯一的翻译,不知道如何使它工作。

服务 API缺少addTranslations方法文档。

将不胜感激任何帮助。

标签: javascriptember.jsinternationalizationember.js-2ember-intl

解决方案


这是我在进行异步翻译时使用的(随着应用程序的增长,我可能会将其带回来)

这是在services/intl.ts

import IntlService from 'ember-intl/services/intl';
import fetch from 'fetch';

import config from 'emberclear/config/environment';

export default class EmberClearIntl extends IntlService {
  async loadTranslations(locale: string) {
    let response = await fetch(`${config.hostUrl}/translations/${locale}.json`);
    let translations = await response.json();

    this.addTranslations(locale, translations);
  }

  lookup(key: string, localeName: string, options: any = {}) {
    const localeNames = this.localeWithDefault(localeName);
    const translation = this._adapter.lookup(localeNames, key);

    if (!options.resilient && translation === undefined) {
      const missingMessage = this._owner.resolveRegistration('util:intl/missing-message');

      return missingMessage.call(this, key, [localeNames]);
    }

    return translation;
  }
};

我相信它的灵感来自 ember-intl 存储库中的一个 github 问题,我对其进行了修改以适应我的设置。(例如,config.hostUrl 的东西——目前它只是设置为我的域,但如果您的站点没有部署在域的根目录下,它可能会很方便)。

我的申请路线中的用法:

import Route from '@ember/routing/route';
import { service } from '@ember-decorators/service';

import EmberClearIntl from 'emberclear/services/intl';

export default class ApplicationRoute extends Route {
  @service intl!: EmberClearIntl;

  async beforeModel() {
    const locale = 'en-us';

    await this.intl.loadTranslations(locale);

    this.intl.setLocale(locale);
  }
}

我还没有弄清楚如何使用渐进式 Web 应用程序最好地管理异步翻译。在我的应用程序的当前版本中,我删除了异步行为,并将翻译文件(只有一个)与我的应用程序捆绑在一起。


推荐阅读