Request Two Models together

 ̄綄美尐妖づ 提交于 2020-01-22 07:10:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!