我试图在同一条路线上加载两个不同的模型,我发现堆栈溢出说明我可以使用Ember.RSVP.hash()
来完成这项工作,这就是我做过的工作它有效。
model: function(params) {
return Ember.RSVP.hash({
flyer: this.store.find('flyer', params.flyer_id),
images: this.store.find('image', '-Jrgar1tSArUw-_PiJqX')
});
},
正如您所看到的,我已经硬编码了我需要加载的图像记录的ID,这应该来自返回的传单,如flyer.imagesID
但是当我这样做时,我在控制台中出现错误,这是堆栈跟踪......
Error while processing route: flyers flyer is not defined ReferenceError: flyer is not defined
at model (http://localhost:4200/assets/flyer-creator.js:338:38)
at EmberObject.default.extend.deserialize (http://localhost:4200/assets/vendor.js:32872:19)
at applyHook (http://localhost:4200/assets/vendor.js:55667:32)
at Object.HandlerInfo.runSharedModelHook (http://localhost:4200/assets/vendor.js:53668:22)
at Object.subclass.getModel (http://localhost:4200/assets/vendor.js:53894:21)
at __exports__.bind (http://localhost:4200/assets/vendor.js:55536:19)
at tryCatch (http://localhost:4200/assets/vendor.js:55993:16)
at invokeCallback (http://localhost:4200/assets/vendor.js:56005:17)
at publish (http://localhost:4200/assets/vendor.js:55976:11)
at http://localhost:4200/assets/vendor.js:37026:7
有没有办法访问下一个属性中哈希返回的传单属性?
答案 0 :(得分:5)
Ember.RSVP.hash()可以避免编码实际的承诺顺序。如果订单很重要,您可以使用promise chaining。
model: function(params) {
var self = this;
return this.store.find('flyer', params.flyer_id).then(function(flyer) {
return Ember.RSVP.hash({
flyer: flyer,
images: self.store.find('image', flyer.get('imagesID'))
});
});
},
在您的特殊情况下,您使用路线动态参数params.flyer_id
,因此更好的方法:
flyer
images
。原因是当您将传单模型直接传递到路由{{link-to 'flyer' 'flyer' flyer}}
或transitionTo('flyer', flyer)
时,不会触发模型挂钩。
model: function(params) {
return this.store.find('flyer', params.flyer_id);
},
afterModel: function(flyer) {
var self = this;
// flyer is model already resolved
return this.store.find('image', flyer.get('imagesID')).then(function(images) {
var controller = self.controllerFor( self.get('controllerName') );
controller.set('images', images);
// or 2 steps:
// 1) self.set('images', images) here
// 2) implement setupController hook, it has controller as param
});
}
PS如果flyer belongsTo image
你可以使用承诺
flyer.get('image')
而不是
this.store.find('image', flyer.get('imageID'))