transitionTo, refresh, currentRouteName — Anywhere
The Router Service
The router service exposes navigation APIs and current-route info from components, services, anywhere.
What you'll learn
- Inject the router service
- Call transitionTo to navigate programmatically
- Read currentRouteName for the active route
The router service is Ember’s public surface for routing. It used to be that
only routes could navigate; now you inject router anywhere and call its
methods.
Inject
import Component from '@glimmer/component';
import { service } from '@ember/service';
import { action } from '@ember/object';
export default class SaveAndGo extends Component {
@service router;
@action
async save() {
const post = await this.args.draft.save();
this.router.transitionTo('post.show', post.id);
}
} Common Methods
transitionTo(name, ...models, queryParams)— navigate, push historyreplaceWith(name, ...models)— navigate, replace historyrefresh()— re-run the current route’smodelhookurlFor(name, ...models)— build a URL string without navigating
Reading Current State
These are @tracked so templates update automatically:
currentRouteName— string like'post.show'currentURL— string like'/posts/42'currentRoute— the activeRouteInfoobject
{{#if (eq this.router.currentRouteName "settings.index")}}
<p>You're on settings.</p>
{{/if}} Listening For Transitions
The router service emits events you can subscribe to in init or a setup
hook:
constructor() {
super(...arguments);
this.router.on('routeWillChange', this.beforeNav);
this.router.on('routeDidChange', this.afterNav);
} The routeWillChange handler can call transition.abort() to cancel.
Query Params
Pass query params with the magic last argument:
this.router.transitionTo('posts', {
queryParams: { sort: 'createdAt', filter: 'mine' },
});