Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access params in the afterModel hook

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?

like image 647
Christian Fazzini Avatar asked Dec 28 '25 16:12

Christian Fazzini


2 Answers

Use the this.paramsFor(this.routeName) function to get a plain object with the params in.

like image 83
Epirocks Avatar answered Dec 30 '25 06:12

Epirocks


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);
  });
}
like image 40
Piotr Avatar answered Dec 30 '25 07:12

Piotr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!