2016-08-09 44 views
0

我正在開發一個簡單的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); 
    } 
}); 

助手(應用程序/傭工/ translate.js):

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

     return i18n.translate(params[0]); 
    } 
}); 

回答

1

我只是找到了一個 '解決方案'。每次'語言環境'屬性更改時,我都會重新計算助手。這就是我的幫手現在的樣子:

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]); 
    } 
});