0

So I have a route with this model:

model() {
   var self = this;
   return RSVP.hash({
    comptes : this.get('store').findAll('compte'),
    contrats: 
    this.get('store').findAll('contrat').then(function(contrats) {
      return contrats.filterBy("contrat_fk.id", 
         self.get('currentContract.contrat.id'));
      }),
    })
  }

My goal is to filter the model contrat with the value provided by my service currentContract.

It works fine when the page is reloaded, but when I change the route and comeback to this route, the model doesn't seem to be loaded and I have to reload the page to see it.

And I don't really wan't to use query params and put the contract id in the URL

El Poisen
  • 121
  • 1
  • 8

1 Answers1

1

Move the filter logic to a computer property in the controller. Then everything will work fine when the dependency key is right.

For example in your route you can do this:

model() {
  return this.store.findAll('contrat');
}

and next in your controller this:

currentContract: service(),
filteredContracts: computed('currentContract.contrat.id', 'model.@each.id', {
  get() {
    const cci = this.currentContract.contrat.id;
    return this.model.filter(c => c.id === cci);
  }
}),

be careful: this code uses the . for getters, which works for ember 3.1. For older versions you need to use .get().

Lux
  • 17,835
  • 5
  • 43
  • 73
  • So for example, in my route I get my model with findAll('nameofmodel'). And then in my controller I define a computed property with my model and I filter this.get('model') ? – El Poisen Apr 16 '18 at 11:34
  • 1
    basically yes. I've inserted an example. – Lux Apr 16 '18 at 13:17
  • Thank you very much for taking the time to help me! I think i'm gonna stick with only my service which provides me the current contract and all the infos I need but your answer will definitively help me! – El Poisen Apr 16 '18 at 18:24
  • I'm not sure what you mean. my code example *does* use your service. it just moves code from the route to the controller. – Lux Apr 16 '18 at 20:18
  • Yes you are totally right but for my case here, I can use my contract given by my service and I don't need a controller that's what I meant. I was a bit confused with service and controller. I desperately wanted to get the contract id with my service and then use it to filter my model. But now I am simply setting all my contract in my service instead of just the id. I got a bit lost in the process, I'm sorry if I was unclear in my request. – El Poisen Apr 16 '18 at 21:03
  • If you're still here I have a last question. Is it possible to inject a service into a route and access the service in my route's template without using a controller? – El Poisen Apr 17 '18 at 14:47
  • 1
    you *always* use a controller. you can use `setupController` or return data from your `model` hook, but this always uses the controller. and actually you *should* use a controller. – Lux Apr 17 '18 at 15:44