Class RouterService

public

The Router service is the public API that provides access to the router.

The immediate benefit of the Router service is that you can inject it into components, giving them a friendly way to initiate transitions and ask questions about the current global router state.

In this example, the Router service is injected into a component to initiate a transition to a dedicated route:

1
2
3
4
5
6
7
8
9
10
11
12
import Component from '@ember/component';
import { inject as service } from '@ember/service';

export default Component.extend({
  router: service(),

  actions: {
    next() {
      this.router.transitionTo('other.route');
    }
  }
});

Like any service, it can also be injected into helpers, routes, etc.

Show:

Module: @ember/routing
transition
Transition

The routeDidChange event only fires once a transition has settled. This includes aborts and error substates. Like the routeWillChange event it receives a Transition as the sole argument.

A good example is sending some analytics when the route has transitioned:

form.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import {inject as service} from '@ember/service';

export default Route.extend({
  router: service('router'),
  init() {
    this._super(...arguments);
    this.router.on('routeDidChange', (transition) => {
      ga.send('pageView', {
        current: transition.to.name,
        from: transition.from.name
      });
    })
  }
});
Module: @ember/routing
transition
Transition

The routeWillChange event is fired at the beginning of any attempted transition with a Transition object as the sole argument. This action can be used for aborting, redirecting, or decorating the transition from the currently active routes.

A good example is preventing navigation when a form is half-filled out:

form.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import {inject as service} from '@ember/service';

export default Route.extend({
  router: service('router'),
  init() {
    this._super(...arguments);
    this.router.on('routeWillChange', (transition) => {
      if (!transition.to.find(route => route.name === this.routeName)) {
        alert("Please save or cancel your changes.");
        transition.abort();
      }
    })
  }
});

The routeWillChange event fires whenever a new route is chosen as the desired target of a transition. This includes transitionTo, replaceWith, all redirection for any reason including error handling, and abort. Aborting implies changing the desired target back to where you already were. Once a transition has completed, routeDidChange fires.