承诺完成后如何向帮助者注入服务?

Ama*_*yla 4 ajax promise ember.js ember-cli es6-promise

我正在开发一个简单的 Ember 应用程序,它从 API 检索所有语言字符串。我已经使用一种translate()方法设置了一个服务,并将该服务注入到一个帮助程序中。问题是我想使用它的属性在助手中不可用,因为当它被使用时,承诺还没有兑现。从服务加载后,如何访问助手中的属性?

服务(应用程序/服务/i18n.js):

export default Ember.Service.extend({
    locales: null,
    init() {
        this._super();

        Ember.$.getJSON('/api/recruiting/locales').then(function (response) {
            this.set('locales', response.data);
        }.bind(this));
    },
    translate(key) {
        // This causes the problem: locales property has not been loaded yet at this point
        return this.get('locales.' + key);
    }
});
Run Code Online (Sandbox Code Playgroud)

助手(app/helpers/translate.js):

export default Ember.Helper.extend({
    i18n: Ember.inject.service(),
    compute(params/*, hash*/) {
        var i18n = this.get('i18n');

        return i18n.translate(params[0]);
    }
});
Run Code Online (Sandbox Code Playgroud)

Ama*_*yla 5

我刚刚找到了一个“解决方案”。每次“区域设置”属性发生变化时,我都会重新计算助手。这是我的助手现在的样子:

export default Ember.Helper.extend({
    i18n: Ember.inject.service(),
    onLocalesInit: Ember.observer('i18n.locales', function () {
        this.recompute();
    }),
    compute(params/*, hash*/) {
        var i18n = this.get('i18n');

        return i18n.translate(params[0]);
    }
});
Run Code Online (Sandbox Code Playgroud)