简体   繁体   中英

Ember store not loading nested hasMany relationship data

I am making a call to an API I built. The response returns a big JSON with all the data nested within it. Example:

"feed" : {
  "id": 12345,
  "name": "trogdor",
  "items": [
    {
      "id":6789,
      "content": I am an items content
    },
    {
      "id":6789,
      "content": I am an items content
    },
    {
      "id":6789,
      "content": I am an items content
    },
    {
      "id":6789,
      "content": I am an items content
    }
  ]
}

So as you can see, the Feed model which is return hasMany items.

So my models are defined as such:

Feed Model:

export default DS.Model.extend({
  name: attr('string'),
  items: hasMany('item')
});

Item Model:

export default DS.Model.extend({
  content: attr('string'),
  items: belongsTo('feed')
});

But when the promise is return from my model call, no data is set when I call for the model's "items". Instead I just get a store class with no attributes or data.

When I log the model and try to open the data hash, i get an ember EmptyObject which has no data.

Using Ember CLI, generate a new serializer for your feed model: ember g serializer feed

Then, define the serializer as follows:

import DS from 'ember-data';
import ApplicationSerializer from './application';

export default ApplicationSerializer.extend(DS.EmbeddedRecordsMixin, {
   attrs: {
     items: { embedded: 'always'},
   }
});

Make sure you are extending the DS.RESTadapter in your main application.js adapter file in order for Ember to properly serialize your embedded nested JSON data, otherwise Ember will expect the payload from your server to be in the JSON API format.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM