如何使用EmberJS在路由中加载belongsTo/hasMany关系

Kar*_*sen 9 ember.js ember-data

在我的EmberJS应用程序中,我显示了一个约会列表.在AppointmentController中的一个动作中,我需要获得约会所有者,但是所有者总是返回"undefined".

我的文件:

车型/ appointment.js

import DS from 'ember-data';

export default DS.Model.extend({
    appointmentStatus: DS.attr('number'),
    owner: DS.hasMany('person'),
    date: DS.attr('Date')
});
Run Code Online (Sandbox Code Playgroud)

车型/ person.js

import DS from 'ember-data';

export default DS.Model.extend({
    name: DS.attr('string')
});
Run Code Online (Sandbox Code Playgroud)

模板/ appointmentlist.js

{{#each appointment in controller}}
    <div>
        {{appointment.date}} <button type="button" {{action 'doIt'}}>Do something!</button>
    </div>
{{/each }}
Run Code Online (Sandbox Code Playgroud)

控制器/ appointmentlist.js

export default Ember.ArrayController.extend({
    itemController: 'appointment'
});
Run Code Online (Sandbox Code Playgroud)

控制器/ appointment.js

export default Ember.ObjectController.extend({
    actions:{
        doIt: function(){
            var appointment = this.get('model');
            var owner = appointment.get('owner'); //returns undefined
            //Do something with owner
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

现在,我知道我可以将owner-property更改为owner: DS.hasMany('person', {async: true}),然后处理从中返回的promise appointment.get('owner');,但这不是我想要的.我发现如果我在约会列表模板中执行此操作{{appointment.owner}}或此操作{{appointment.owner.name}},则会从服务器获取所有者记录.所以我猜Ember不会加载关系,除非它们在模板中使用.

我认为我的问题的解决方案是使用预约列表路由来获取belongsTo关系中的记录.但我无法弄清楚如何.

也许是这样的?

路线/ appointmentlist.js

export default Ember.Route.extend({
    model: function() {
        return this.store.find('appointment');
    },
    afterModel: function(appointments){
        //what to do
    }
});
Run Code Online (Sandbox Code Playgroud)

编辑

我这样做了:

路线/ appointmentlist.js

export default Ember.Route.extend({
    model: function() {
        return this.store.find('appointment');
    },
    afterModel: function(appointments){
         $.each(appointments.content, function(i, appointment){

                var owner= appointment.get('owner')   
         });
    }
});
Run Code Online (Sandbox Code Playgroud)

它有效,但我不喜欢这个解决方案......

Kin*_*n2k 21

您仍然异步加载这些记录,因此如果您足够快,您仍然可能未定义.最好从afterModel钩子返回一个promise,或者只是修改模型钩子来完成所有操作.

model: function() {
  return this.store.find('appointment').then(function(appointments){
    return Ember.RSVP.all(appointments.getEach('owner')).then(function(){
      return appointments;
    });
  });
}
Run Code Online (Sandbox Code Playgroud)

要么

model: function() {
  return this.store.find('appointment');
},
afterModel: function(model, transition){
  return Ember.RSVP.all(model.getEach('owner'));
}
Run Code Online (Sandbox Code Playgroud)