问题
I have two models that are many to many. They're used on the first page of my app and I'm having trouble loading them.
Both models only have a handful of items (<200) and I'd like to just load both models completely in one findAll
request each. But as the first model gets loaded, Ember starts fetching the missing data for the second model, item by item. If I try to just load the models separately, I get an error and have to set {async:true}
for the hasMany
attr. For some reason though, Ember isn't recognizing the json of the requests for the second model.
Is there anyway to fetch both models and wait till the both load before continuing?
Thanks.
回答1:
I'm guessing you are doing something along the lines of:
App.IndexRoute = Ember.Route.extend({
model: function() {
// Fetch the records of the first model
return this.store.find('post');
},
setupController: function(controller, model) {
this._super(controller, model);
this.store.find('comment').then(function(comments) {
controller.set('comments', comments)
});
}
});
Any promise returned from the model
hook of the route, will cause the router to pause transitioning until that promise is fulfilled. In the above case, the router will wait only for the posts
request to resolve. Therefore we need to instruct the router to wait for both requests to complete.
Enter Ember.RSVP.all and Ember.RSVP.hash. These methods allow for merging multiple promises into one. They return a new promise that is fulfilled only when all of the individual promises are fulfilled. Here is how you do it with Ember.RSVP.hash
:
App.IndexRoute = Ember.Route.extend({
model: function() {
var store = this.store;
return Ember.RSVP.hash({
posts: store.find('post'),
comments: store.find('comment')
});
},
setupController: function(controller, models) {
var posts = models.posts;
var comments = models.comments;
controller.set('content', posts);
controller.set('comments', comments);
}
});
来源:https://stackoverflow.com/questions/19331835/request-two-models-together