EmberJS: How to load multiple models on the same route?

Viewed 25150

While I am not new to web development, I am quite new to to client-side MVC frameworks. I did some research and decided to give it a go with EmberJS. I went through the TodoMVC guide and it made sense to me...

I have setup a very basic app; index route, two models and one template. I have a server-side php script running that returns some db rows.

One thing that is very confusing me is how to load multiple models on the same route. I have read some information about using a setupController but I am still unclear. In my template I have two tables that I am trying to load with unrelated db rows. In a more traditional web app I would have just issued to sql statements and looped over them to fill the rows. I am having difficulty translating this concept to EmberJS.

How do I load multiple models of unrelated data on the same route?

I am using the latest Ember and Ember Data libs.

Update

although the first answer gives a method for handling it, the second answer explains when it's appropriate and the different methods for when it isn't appropriate.

6 Answers

Taking the accepted answer, and updating it for Ember 3.16+

app/routes/index.js

import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';

export default class IndexRoute extends Route {
  @service store;

  async model() {
    let [people, companies] = await Promise.all([
      this.store.findAll('person'),
      this.store.findAll('company'),
    ]);


    return { people, companies };
  }

}

Note, it's recommended to not use setupController to setup aliases, as it obfuscates where data is coming from and how it flows from route to template.

So in your template, you can do:

<h2>People:</h2>

<ul>
  {{#each @model.people as |person|}}
    <li>{{person.name}}</li>
  {{/each}}
</ul>

<h2>Companies:</h2>

<ul>
  {{#each @model.companies as |company|}}
    <li>{{company.name}}</li>
  {{/each}}
</ul>
Related