Component backed by a model

Hello,

I wan’t to create a navigation bar, with a list of items that comes from a RESTful service, I thought that the best way to do this is creating a new Component backed by a Model. I’m wrong?, if so, which is the best practice to achieve this?

import Ember from 'ember';

export default Ember.Component.extend({
  model: function() {
    return this.store.findAll('profile');
  },
});

Is this possible? Thanks in advance.

You should fetch the model in the route, then pass the object to the component in the route’s template.

1 Like

There are two problems with this snippet, model is a hook in Ember.Route, and store is not available in Ember.Component. Even if store was available, if you tried to bind {{model}} in the template you would get the actual function, and not the result since it’s not a computed property.

The best practice is to load the data necessary in the parent route of the component. If the component is inserted in the application template, then you should load the data in the application route. Something like:

// app/routes/application.js
export default Ember.Route.extend({
  model() {
    return this.store.findAll('profile');
  }
});

// app/templates/application.hbs
{{your-component profiles=model}}

If you have more than one model you want to return in your model hook:

// app/routes/application.js
export default Ember.Route.extend({
  model() {
    return Ember.RSVP.hash({
      profiles: this.store.findAll('profile'),
      somethingElse: this.store.findAll('something-else')
    });
  }
});

// app/templates/application.hbs
{{your-component profiles=model.profiles}}

If you need more specific help try posting more of your code, or reproducing it in Ember Twiddle.

1 Like

Thank you guys! Really clear responses!