Search code examples
ember.jsember-data

Accessing Store data in service Ember js


I am trying to peek a store from the service, by injecting the store in my service. The peekRecord function returns a Class. What is the best way to access the record that the store returns?

As peekRecord is synchronous I tried like:

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

Is there any Ember specific way to access the record that's returned from the store?


Solution

  • Use Ember.Object's get() to retrieve value and set() method to update the value.

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

    where someProperty could defined upon the model:

    import Model from 'ember-data/model';
    import attr from 'ember-data/attr';
    
    export default Model.extend({
        someProperty: attr('string');
    });
    

    Using these methods will also make sure computed properties are recomputed (by default, if depending values have changed in the meantime). I highly recommend reading through this section of the Ember guides: The Object model.

    Btw, personally, as I switched to ESLint from JSHint and applied eslint-plugin-ember, I use get() and set() methods from Ember namespace. In such a case, instead of writing hasPermission.get('data') you would write Ember.get(hasPermission, 'data');. Bringing it even further when it comes to code readability, you could do sth like this:

    // 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'));
       },
    });
    

    The following Stackoverflow thread touches slightly the difference between this.get() and Ember.get().