我正在尝试实现翻译的异步获取。我将 publicOnly
设置为 true
作为 docs说:
// config/ember-intl.js
module.exports = function() {
return {
publicOnly: true
}
};
跳过设置 locales
键的步骤,因为翻译存储在 /translations
文件夹中。
接下来,我应该修改 beforeModel
Hook 以异步获取翻译,这就是文档非常模糊的地方:
// 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);
在运行时,我在 dist
文件夹中的任何地方都没有 translations.json
文件。我有 dist/translations/en-us.json
只是我唯一的翻译,不知道如何让它工作。
Service 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);
}
}
我还没有弄清楚如何使用渐进式网络应用程序最好地管理异步翻译。在我的应用程序的当前版本中,我删除了异步行为,并将翻译文件(只有一个)与我的应用程序捆绑在一起。
关于javascript - 使用 ember-intl 异步加载翻译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51885378/