How to use nested call to datastore in ember.js?

by darrion.kuhn , in category: Javascript , a month ago

How to use nested call to datastore in ember.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by cali_green , a month ago

@darrion.kuhn 

In Ember.js, you can make nested calls to the datastore by using the model hook in your route or controller to fetch related data. Here's an example:

  1. Define your route handler with nested calls to fetch related data:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
// app/routes/posts.js
import Route from '@ember/routing/route';

export default Route.extend({
  model() {
    return this.store.findAll('post').then(posts => {
      return posts.map(post => {
        return post.get('comments').then(comments => {
          post.set('comments', comments);
          return post;
        });
      });
    });
  }
});


  1. Access the nested data in your template by iterating over the nested model:
1
2
3
4
5
6
7
8
9
{{!-- app/templates/posts.hbs --}}
{{#each model as |post|}}
  <h2>{{post.title}}</h2>
  <ul>
    {{#each post.comments as |comment|}}
      <li>{{comment.body}}</li>
    {{/each}}
  </ul>
{{/each}}


With this setup, when you visit the /posts route, Ember.js will first fetch all posts from the datastore and then fetch all comments related to each post. The nested data will be available in the template for display.