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:

app/components/example.js
import Component from '@glimmer/component';
import { action } from '@ember/object';
import { service } from '@ember/service';

export default class ExampleComponent extends Component {
  @service router;

  @action
  next() {
    this.router.transitionTo('other.route');
  }
}

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

Show:

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:

app/routes/contact-form.js
import Route from '@ember/routing';
import { service } from '@ember/service';

export default class extends Route {
  @service router;

  activate() {
    this.router.on('routeDidChange', (transition) => {
      ga.send('pageView', {
        current: transition.to.name,
        from: transition.from.name
      });
    })
  }
}

routeDidChange will be called after any Route's didTransition action has been fired. The updates of properties currentURL, currentRouteName and currentRoute are completed at the time routeDidChange is called.

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:

app/routes/contact-form.js
import Route from '@ember/routing';
import { service } from '@ember/service';

export default class extends Route {
  @service router;

  activate() {
    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.