First of all am new to ember …
I am creating an ember service like the below and wanna use ember data for some functionalities is it possible ?
import Ember from 'ember';
export default Ember.Service.extend({
init() {
this._super(...arguments);
this.get('store')
console.log(this.get('store')); //undefined
}
});
How can i access stores inside service ?
1 Like
You just needs to inject the store service.
```js
import Ember from 'ember';
export default Ember.Service.extend({
store: Ember.inject.service(),
init() {
this._super(...arguments);
console.log(this.get('store'));
}
});
4 Likes
does this apply in the current version of ember js
Yep, it hasn’t changed, except that you can now use native classes, native getters, and much nicer imports! The example above should be written like this today:
import Service, { inject as service } from '@ember/service';
export default class MyService extends Service {
@service store;
constructor() {
super(...arguments);
console.log(this.store);
}
}
For details on what all those pieces mean, you likely want to read through the Ember Guides’ section on services. If you aren’t familiar with some of the modern JavaScript concepts (and a lot has changed, so that’s quite reasonable), you may want to read this section on JavaScript classes as well.
2 Likes
This is my task.js. I want to access the store on this component everything works fine. Is their anything I can Improve on?
`
import Component from ‘@ember/component’;
import { inject as service } from ‘@ember/service’;
export default Component.extend({
store: service(),
actions: {
updatePin(id) {
this.store.findRecord('task', id).then(function (task) {
const {isPined} = task;
console.log(task)
// ...after the record has loaded
task.isPined = !isPined;
});
}
}
})`
This should work fine; but a few notes:
-
// after the record has loaded
By the time you’re in the .then
block you have loaded it; that’s what the resolution of the findRecord
promise means.
-
Instead of doing function(task) { ... }
as the callback you can (and generally should, here) use an “arrow function” instead, so that you don’t re-bind this
:
this.findRecord('task', id).then((task) => {
// ...
});
-
You’ll need to actually save the updated task
when you’re done:
task.save();
You may find it more convenient to write it using async
/await
syntax:
import Component from '@ember/object';
import Service, { inject as service } from '@ember/service';
import { action } from '@ember/object';
export default Component.extend({
store: service(),
actions: {
async updatePin(id) {
let task = await this.store.findRecord('task', id);
const {isPined} = task;
task.isPined = !isPined;
task.save();
}
}
}
1 Like