I am developing a simple Ember app, which retrieves all language strings from an API. I have setup a service with a translate()
method, and injected that service into a helper. The problem is that the property I want to use it not available in the helper, because when it's used, the promise hasn't been fulfilled yet. How can I access the property in the helper after it has been loaded from the service?
Service (app/services/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);
}
});
Helper (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]);
}
});
I just found a 'solution'. I am recomputing the helper every time the 'locales' property changes. This is how my helper looks now:
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]);
}
});