Pergunta

I have an Ember app that, rather than using Ember Data, uses our own custom AJAX data layer to talk to an API.

We're able to load two models at once using RSVP - one is a Project object via our API wrapper, the second is an object representing the logged in user. Both are passed into the controller and templates and work just fine.

But I have a need to load a second model, based on a value in the returned Project object.

Once I've loaded a model in my route like this...

App.ProjectUpdateRoute = Ember.Route.extend({

    setupController: function(controller, model) {
        controller.set('model', model);
    },

    model: function(params) {

        return Ember.RSVP.hash({
            // Load Project from API - /myapi/v1/Project/:ProjectID
            Project : App.Project.create().findById(params.ProjectID),
            // Load current user from local object
            User : App.AuthUser,
        });
    },
});

...I have a Project object (or rather model.Project) with various properties including the ID of the User that owns the project.

Now I'd like to make a second API call to /myapi/v1/User/:UserID to get the User's details.

Everything I've tried - including adding further App.User.create().findById(UserID) calls into the route's setupController function and the controller - results in the correct API call, but it's asyncronous, so Ember carries on rendering the page and I can't show the result of the API call on the page.

So - how, and where in the Ember structure, do I load a second model based on data from the first? How can I get ember to wait for the resolved promise of this second AJAX call?

UPDATE

I've also tried using afterModel:function() which is almost what I need - it makes the second API call in the right place in the app flow, but I still need to add the result into my existing model array:

afterModel: function(model, tranistion, params) {

    // Returns the promise but doesn't update 'model'
    return Ember.RSVP.hash({
        ProjectOwner : App.User.create().findById(model.Project.UserID)
    });
}
Foi útil?

Solução

Chain the promise, and Ember will take the final resultant (from the model hook)

model: function(params) {

  return Ember.RSVP.hash({
      // Load Project from API - /myapi/v1/Project/:ProjectID
      Project : App.Project.create().findById(params.ProjectID),
      // Load current user from local object
      User : App.AuthUser,
    }).then(function(results){
      return App.User.create().findById(results.Project.UserID).then(function(user){
        results.projectUser = user;
        return results;
      });
    });
},
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top