Search code examples
ember.jsroutesember-datamodels

Ember.js v2 Load multiple models in route without making separate requests


Just getting started with Ember.js, so after a workign myself through the various tutorials online for a couple of weeks(…), I really can't puzzle out the following question.

I want to display 4 models on 1 route. How can I do that, while avoiding making 4 server calls?

More inforamtion:

I want to display records of type "person", "quote", "product" and "case" on my index page.

In my index route, (routes/index.js) I can load them using:

import Ember from "ember";

export default Ember.Route.extend({
  model(){
    return Ember.RSVP.hash({
      persons : this.get('store').findAll('person'),
      quotes  : this.get('store').findAll('quote'),
      cases   : this.get('store').findAll('case'),
      products: this.get('store').findAll('product')
    });
  }
});

(And in my adapter, adapters/application.js, I have: )

import DS from "ember-data";

export default DS.JSONAPIAdapter.extend({
  host       : 'http://localhost:8080/dummy.php',
  pathForType: function (type) {
    return "?type=" + type;
  }
});

This works very nicely :), but ember.js makes 4 requests:

enter image description here

However, I could easily provide a JSON file that provides records of all 4 types.

So, how can I tell ember.js:

"Here's a nice large JSON file, full of records. Now, use only records of the 'person'-type for the person model, and idem dito for 'case', 'quote' and 'product'

?


Solution

  • Nothing wrong in loading model per request. If models are related then you should consider defining relationship between them. again for loading any async data it will make network request.

    If you want to load data in single request for different model type, then you can try the below, this is not ember-data way. so I will not encourage this.

    import Ember from "ember";
    
    const {RSVP} = Ember;
    
    export default Ember.Route.extend({
      model() {
        return RSVP
          .resolve(Ember.$.getJSON('http://localhost:8080/dummy.php'))
          .then((result) => {
            this.get('store').pushPayload(result);
            return {
              persons : this.get('store').peekAll('person'),
              quotes  : this.get('store').peekAll('quote'),
              cases   : this.get('store').peekAll('case'),
              products: this.get('store').peekAll('product')
            };
          });
      }
    });