I am using ember 2.3. When I tried to access store inside a component, I am getting the following error in console.

This is what I have tried in component.js
export default Ember.Component.extend({
actions: {
saveEmployee : function() {
var store = this.store;
var newEmployee = store.createRecord("employee", {
fname: "Manu",
lname: "Benjamin",
email: "[email protected]",
department: "IT Services"
});
newEmployee.save().then(()=> {
console.log("Record successfully saved!!!!");
});
}
}
});
Do I need to include anything to use store in my component?
I was trying to figure out the reason for this type error. At last I found the solution from the following blog by Josh Farrant.
https://blog.farrant.me/how-to-access-the-store-from-within-an-ember-component/
we need to inject the store service in component.
store: Ember.inject.service(),
we can use the store injected in actions using the get function,
let store = this.get('store');
I modified my code using the above solution and it worked for me.
export default Ember.Component.extend({
store: Ember.inject.service(),
actions: {
saveEmployee : function() {
var store = this.get('store');
var newEmployee = store.createRecord("employee", {
fname: "Manu",
lname: "Benjamin",
email: "[email protected]",
department: "IT Services"
});
newEmployee.save().then(() => {
console.log("Record successfully saved!!!!");
});
}
}
});
Thanks Josh Farrant for the nice blog.
This topic has been already discussed multiple times and I am sure you can find many posts on the issue. Let me repeat shortly what has been mentioned already: try to avoid using store directly within a component.
In case your design allows you to manipulate Ember store in an associated route or a controller (where the store is btw available by default), try to send an action from a component so that it bubbles to the controller and performs a store manipulation in the controller. May EmberJS guides - how to send actions from components help you with that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With