Global query parameters with Ember

Recently while using Ember.js I needed to use global query parameters across routes. For example, navigating from /users?start=2017-01-01 to /users/1?start=2017-01-01 I wanted to make sure the start filter was applied across routes.

This can be achieved by using services and computed properties.

As you can see in the example below, the date.js service will handle the state across the lifetime of the application.

// app/services/date.js
import Ember from 'ember';
import moment from 'moment';

export default Ember.Service.extend({
  start: moment().startOf('day').format('YYYY-MM-DD'),
  end: moment().endOf('day').format('YYYY-MM-DD'),

  setDates(dates){
    this.set('start', dates.dateFrom);
    this.set('end', dates.dateTo);
  }
});

In any controller that needs the query parameters, inject the service and use the alias computed property. This creates a new property that points at date.start.

// app/controller/users.js
import Ember from 'ember';

export default Ember.Controller.extend({
  date: Ember.inject.service(),

  dateFrom: Ember.computed.alias('date.start'),
  dateTo: Ember.computed.alias('date.from'),

  actions: {
    update(dateFrom, dateTo) {
      this.get('date').setDates({ dateFrom, dateTo });
    },
  },

  queryParams: ["dateFrom", "dateTo"]
});

When the update action is called, the service updates the properties on the date service.


Published on .