javascript - 使用 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
方法文档。
将不胜感激任何帮助。
解决方案
这是我在进行异步翻译时使用的(随着应用程序的增长,我可能会将其带回来)
这是在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 应用程序最好地管理异步翻译。在我的应用程序的当前版本中,我删除了异步行为,并将翻译文件(只有一个)与我的应用程序捆绑在一起。
推荐阅读
- android - 尝试构建我的 Android 版本时,我在 Unity2019.4.23f1c1 中收到以下 gradle 错误
- html - 无法设置自定义滚动条的样式
- angular - Ant Zorro 相当于 Antd 中的 generatePicker
- python-3.x - conda activate 在 VS 代码中未按预期工作
- python - 使用 Python 计算从一张纸到另一张纸的匹配百分比
- c# - 使用 AR Foundation 将屏幕触摸位置转换为 AR 中的世界位置
- java - Mac OS 和 Windows 中的 Selenium
- spring - 授权代码流后,Spring OAuth2 服务器未使用刷新令牌响应
- delphi - Delphi XE:为什么File->New->Other->ActiveX中的一些项目是灰色的?[解决了]
- operating-system - 超线程可以解决哪些问题?