11

I want to redirect from a route, /new, and keep the query params for the new route:

As far as I know, the only place to access queryParams is within the model hook of a route.

But I want to redirect in the beforeModel hook:

import Ember from "ember";

export default Ember.Route.extend({
    /**
     * @@override
     * Implicitly create a new applicant, redirecting to the generated ID at /applications/#{id}
     * @param transition
     */
    beforeModel: function(transition) {
        var emptyApplicant = this.store.createRecord("applicant",
                {isPrimary: true}
            ),
            emptyApplication = this.store.createRecord("application");
        emptyApplication.set("applicant", emptyApplicant);
        emptyApplicant.save().then((savedApplicant) => {
            emptyApplication.save().then((savedApplication) => {
                this.transitionTo("applications", savedApplication);
            });
        });
    }
});

While the above code works, the transition will complete without preserving the query params. For example, navigating to applicants/new?agent=35 will not preserve agent=35 in the query param, and will simply redirect to applicants/new instead.

How can I access the queryParams object from the beforeModel hook in my Ember app?

user1429980
  • 6,872
  • 2
  • 43
  • 53

2 Answers2

9

You should be able to pass query parameters to the transitionTo, something along the line of:

this.transitionTo("applications", savedApplication, {
  queryParams: transition.queryParams
});
Patsy Issa
  • 11,113
  • 4
  • 55
  • 74
3

In more modern versions of Ember, the transition object has a to property which contains the query params. Transition no longer has a queryParams property

A redirect to the index route in a beforeModel for example, might look like this:

beforeModel(transition){
  super.beforeModel(...arguments);
  transition.abort();
  this.transitionTo('index', {
    queryParams: transition.to.queryParams
  });
}
mistahenry
  • 8,554
  • 3
  • 27
  • 38