samedi 3 octobre 2015

Ember Data: first access to lazy loaded hasMany relationships removes them from model

a problem with lazy loading ember hasMany relationships drives me crazy right now.

My Ember model has a relationship to other instances:

app/models/apps/app.js import DS from 'ember-data';

export default DS.Model.extend({
    title: DS.attr("string"),
    childApps: DS.hasMany('apps/app', {inverse: 'parentApp', async:true}),
    parentApp: DS.belongsTo('apps/app', {inverse: 'childApps', async:true}),
});

When the route loads the model, with findRecord(), for the first time the Rest API returns something like:

{
  "title":"some title",
  "childApps":[40,36,38,44,54,55,39,51,53],
  "dateCreated":"2015-10-01T03:34:16Z"
  "id":35,
  "version":0,
  "parentApp":null
}

On the first access to the relationships (e.g. in a template with) {{model.childApps.length}} the browser starts lazy loading all related data. All could be retrieved successfully as can be seen in the network log and ember inspector data view. They got all loaded to the store.

But, in the current view, childApps is empty as soon as the records got loaded. {{model.childApps}} {{model.childApps.length}} renders <DS.PromiseManyArray:ember1459> 0

While investigating the error I found out, that as soon as one record got successfully resolved from the backend, it gets removed from the {{model.childApps}} array, and it shrinks step by step to a length of 0.

Therefore I added a computed property to the component where I could set a breakpoint and watch the behavior

childApps: Ember.computed('appData.childApps.[]', function(){
    return this.get("appData.childApps");
}),

I also found out, that if the records are already loaded to the store, eg. if I navigate to the same route a second time, everything works fine.


I finally found a solution how I get the records initialized correctly on first load with adding following to the route

setupController: function(controller, model) {
    model.get("childApps").then(function(data){
        model.reload();
    });
    controller.set('model', model);
}

But I do not think that this is how it should be, right? I'm not really happy with that.

I suppose it's intended to work on first access also without reloading the model in the setupController method.

Anyone an idea what I'm doing wrong?


I'm using ember-cli 1.13.8, ember 2.0.1 and ember-data: 2.0.0

Aucun commentaire:

Enregistrer un commentaire