我正在尝试实现翻译的异步获取。我将publicOnly设置为true,就像docs说的:
// 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);在运行时,dist文件夹中的任何位置都没有translations.json文件。我只为我的一个也是唯一的翻译使用了dist/translations/en-us.json,不知道如何让它工作。
Service API缺少addTranslations方法的文档。
都会很感谢你的帮助。
发布于 2018-08-17 23:02:57
这是我在做异步翻译时使用的(随着我的应用程序的增长,我可能会把它带回来)
这是用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应用程序最好地管理异步翻译。在我的应用程序的当前版本中,我已经删除了异步行为,只将翻译文件(只有一个)与我的应用程序捆绑在一起。
发布于 2019-01-23 19:58:59
您说得对,文档并不清楚-响应对象不是JSON本身。更改fetch的路径并添加translations.json(),而不仅仅是转换:
// app/routes/application.js
export default Ember.Route.extend({
intl: service(),
async beforeModel() {
let translations = await fetch('/translations/en-us.json');
this.intl.addTranslations('en-us', translations.json());
this.intl.setLocale('en-us');
}
});https://stackoverflow.com/questions/51885378
复制相似问题