2017-09-27 55 views
1

我想通過在我的服務中注入商店來從服務中窺探商店。 peekRecord函數返回一個Class。訪問商店返回記錄的最佳方式是什麼?在服務中訪問存儲數據Ember js

由於peekRecord是同步我嘗試這樣的:

const hasPermission = this.get('store').peekRecord('system/permission','PlatformRead'); 
console.log(hasPermission.data); 

是否有訪問從商店返回的記錄的任何灰燼具體方式是什麼?

回答

1

使用Ember.Objectget()檢索值和set()方法來更新值。

hasPermission.get('someProperty'); 
hasPermission.set('someProperty', 'New value of someProperty'); 

其中someProperty可以在模型中定義:

import Model from 'ember-data/model'; 
import attr from 'ember-data/attr'; 

export default Model.extend({ 
    someProperty: attr('string'); 
}); 

使用這些方法也將確保計算的屬性重新計算(默認情況下,如果根據值同時已改變)。我強烈建議閱讀Ember指南的這一部分:The Object model

順便說一句,就個人而言,我從JSHint切換到ESLint和施加eslint-plugin-ember,我使用從灰燼namespaceget()set()方法。 在這種情況下,您不會寫hasPermission.get('data'),而會寫Ember.get(hasPermission, 'data');。把它更進一步,當涉及到代碼的可讀性,你可以做某事像這樣:

// your-app/services/your-service.js 
// ... imports 

const { 
    get, 
    inject, 
    Service, 
} = Ember; 

export default Service.extend({ 
    store: inject.service(), 

    someFunction(){ 
     const hasPermission = this.get('store').peekRecord('system/permission','PlatformRead'); 
     console.log(get(hasPermission, 'someProperty')); 
    }, 
}); 

以下#1 thread觸摸略有this.get()Ember.get()之間的差異。