lkgarrison
lkgarrison

Reputation: 115

How to correctly access Ember model data from controller

I am using Ember.RSVP.hash to access multiple models in an Ember controller:

export default Ember.Route.extend({
    model() {
        return Ember.RSVP.hash({
            categories: this.store.findAll('category')
            languages: this.store.findAll('language'),
            requirementTypes: this.store.findAll('requirement-type')
        });
    },

    setupController: function(controller, models) {
        controller.set('categories', models.categories);
        controller.set('languages', models.languages);
        controller.set('requirementTypes', models.requirementTypes);
    }
});

I have relentlessly Googled how to access this model data in my controller properly. The only way I have found so far feels far too hacky. I just want to have access to the raw HTTP response data that is returned from my api.

However, when I write this.get('categories'), the what I get back is rather ugly and is a much more complex object than what my api returned:

console.log(this.get('categories'))

The "InternalModel" entries contain the actual data in the _data attribute that was returned from my api:

InternalModel entry details

Is there a better, recommended way to access this model data that is returned from my api and passed to the controller via the associated route? I was expecting to be able to access the exact data my api returned with something like this.get('categories') and immediately access the model data my api sent.

Upvotes: 3

Views: 2048

Answers (1)

Igor
Igor

Reputation: 1588

Yes, this is the correct way. Ember data is a persistence layer for ember, you don't have to use it i you don't want to. But it is quite useful and the point is to have a nice way of accessing your data through model objects.

In your case if you loop through one of the collections from the model result, you would get ember records which contain your data. So in the controller you can do:

this.get('categories').forEach(category => {
  // Do something with category data, i.e.
  console.log('Category name:', category.get('name'));
});

Upvotes: 4

Related Questions