Search code examples
ember.jsember-dataember-cliquery-string

Ember alternative to query params with service


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


Solution

  • 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().