Reputation: 19723
I was using an RSVP.hash in my model
hook. But I needed my route to load dynamic data based on the url (which contains a dynamic segment). i.e. this.route('foo', {path: ':id'})
.
So I decided to move some stuff out, to the afterModel
hook instead.
However, I needed to execute the store with params
(for pagination):
model(params) {
this.set('params', params);
return this.store.findRecord('foo', params.foo_id);
},
afterModel: function(model) {
console.log(this.get('params')); // logs the right params
let params = this.get('params');
// This store query needs access to params
this.store.query('bar', { filter: { 'foo-id': model.get('id') }, page: { number: (params.page ? params.page : 1) } }).then(bars => {
this.controller.set('bars', bars);
});
}
setupController(controller, model) {
this._super(controller, model);
this.set('bars', bars);
}
So far I have this, which works:
model(params) {
this.set('params', params);
...
},
afterModel: function(model) {
console.log(this.get('params')); // logs the right params
...
}
But is this the only way to access params
in the afterModel
hook?
Is this approach sane?
Upvotes: 3
Views: 3139
Reputation: 502
Use the this.paramsFor(this.routeName)
function to get a plain object with the params in.
Upvotes: 7
Reputation: 860
The afterModel
hook provides a second argument named transition
. You can get the params from it using a path like this: transition.params.{route-name}.{param-name}
, so considering your example:
//let's say this is BazRoute and BazController:
model(params) {
return this.store.findRecord('foo', params.foo_id);
},
afterModel: function(model, transition) {
const params = transition.params.baz;
console.log(params); // logs the right params
// This store query needs access to params
this.store.query('bar', { filter: { 'foo-id': model.get('id') }, page: { number: (params.page ? params.page : 1) } }).then(bars => {
this.controller.set('bars', bars);
});
}
Upvotes: 5