I’m trying to create a Ember service that calls an API to query data in a database. I want to create this service so I can inject a dataset (an array of objects) in various controllers, components and routes. I’m not sure if this is one of ember’s ‘best practices’ but it seems like it will solve an immediate issue while learning the framework. For this example I have a service called ‘get-data.js’ and I have a component called ‘responsive-table.js’ that i want to have access to an array of objects that I receive from my database. Should I be using a service to make a ajax request to the api every time i need this array? Should I be using ‘ember-data’ and calling to the ‘store’ and use the ‘findAll’ method? Whenever I try to call to the store and comment out the response from a ‘findAll’ I get a class object? Whats the best way to access your server data in components and controllers with ember.js and ‘ember-data’
service
// service
import Ember from 'ember';
const {
Service, inject: { service }, computed, run, set, get
} = Ember;
export default Service.extend({
ajax: service(),
usingJQueryAjax() {
let data = $.get('/api/data').then(function(result ) {
console.log("right here: ", result );
return result;
});
return data
}
});
componet
// component
import Ember from 'ember';
const {
Component, inject, get, set, $
} = Ember;
export default Component.extend({
store: inject.service(),
actions: {
usingStoreDoesntWork() {
var data = get(this, 'store').findAll('nba');
return data;
},
usingJQueryAjax() {
var data = $.getJSON('/api/data').then(function(result) {
console.log("Array I want to return: ", result );
});
return data;
}
}
});
Whats the best approach to get data into a component from an API ?