Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 39 ยท Services and Dependency Injection

Built-in Services - Router, Store and More

Meet the services Ember gives you for free: the router service for navigation and active-route checks, the store for data, and how to build your own helpers on top.

You do not have to write every service yourself. Ember and its common addons ship several that you inject by name, exactly like your own. The two you will use constantly are router, for moving around the app and asking where you are, and store, for loading and saving data with Ember Data. This lesson tours the built-in services and then shows how to put a small router-like service together yourself so you can see how such a thing works inside.

Real Ember vs stand-in. Code blocks with a file name are real Ember and read-only here. Runnable blocks model the ideas in plain JavaScript, since the site cannot run the framework.

The router service

The router service is the programmatic side of the routing system. Where <LinkTo> navigates from a template, the router service navigates from JavaScript, for example after a form is saved.

app/components/login-form.gjs

JavaScript
import Component from '@glimmer/component';
import { service } from '@ember/service';
import { action } from '@ember/object';
import { on } from '@ember/modifier';

export default class LoginForm extends Component {
  @service router;
  @service session;

  @action
  async submit(event) {
    event.preventDefault();
    await this.session.login('ada', 'secret');
    this.router.transitionTo('dashboard');
  }

  <template>
    <form {{on "submit" this.submit}}>
      <button type="submit">Sign in</button>
    </form>
  </template>
}

Its most useful members:

Member Purpose
transitionTo(route, ...models, { queryParams }) go to another route, adding a history entry
replaceWith(route, ...) go to another route without adding a history entry (good for redirects)
currentRouteName the dotted name of the active route, such as posts.post.comments
currentURL the active URL including query parameters
isActive('posts') true if that route (or a child) is currently active
urlFor('posts.post', 7) build a URL string for a route without navigating
refresh() re-run the model hooks of the active route (and its parents)
on('routeDidChange', fn) listen for finished transitions, e.g. to send analytics

Use replaceWith for redirects so the Back button does not bounce the user straight back to the page that redirected them.

Reacting to every navigation

A classic use is sending a page view each time the route changes. A service can subscribe once, when it is created:

app/services/analytics.js

JavaScript
import Service, { service } from '@ember/service';

export default class AnalyticsService extends Service {
  @service router;

  constructor() {
    super(...arguments);
    this.router.on('routeDidChange', (transition) => {
      console.log('page view:', this.router.currentURL, 'from', transition.from?.name);
    });
  }
}

Remember that services are lazy: nothing happens until something reads analytics. Apps usually inject it in the application route (or an initializer) so it starts at boot.

<LinkTo> already adds an active class for the current route. When you need that fact somewhere else, say to highlight a menu section whose links are nested, ask the router service:

JavaScript
get inSettings() {
  return this.router.isActive('settings');
}

Because the router service's properties are tracked, a template using {{this.inSettings}} re-renders after navigation without any extra code.

The store service

The store service belongs to Ember Data. It is the single door through which you read and write records (findAll, findRecord, query, createRecord, saveRecord). Chapter 4 covers it in depth; here is only how it fits the injection picture:

app/routes/posts.js

JavaScript
import Route from '@ember/routing/route';
import { service } from '@ember/service';

export default class PostsRoute extends Route {
  @service store;

  model() {
    return this.store.findAll('post');
  }
}

The store is a singleton service like any other, so every route and component sees the same cache of records. Loading a post in one place makes it instantly available to the rest of the app.

Other services you will meet

Service Where it comes from What it does
router Ember navigation and route state
store Ember Data records and the data cache
page-title ember-page-title sets document.title from templates
intl ember-intl translations and number/date formatting
session ember-simple-auth authentication state
flash-messages addons toast notifications
media addons responsive breakpoints

Your own cart or theme service sits in the same list. Once you know one, you know them all: generate, inject, use.

Building a router service of your own

To understand what the real router service does, we can model its core: a table of routes, a current route, a history stack, and the transitionTo, replaceWith and isActive behaviors. This is a simplified stand-in, not the real router (which also resolves models, nested routes and loading states).

JS Stand-in: a tiny router service

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The history line shows why replaceWith exists: the login entry was overwritten, so Back goes to posts.post, not to the login form.

A service in front of a data store

The store is the most important built-in, and a stand-in for its caching idea is instructive: it keeps one object per type + id, so asking twice returns the same record. That identity guarantee is why changes made in one screen show up in another.

JS Stand-in: an identity-mapped store

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The real store is far richer (relationships, dirty tracking, adapters), but the identity map is its heart, and you will build on it in Ember Data and Models.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which router service method should a login redirect use so the Back button does not return to the login page?

    replaceWith swaps the current history entry instead of adding one, so Back skips the page that redirected.
  2. 2. What does router.isActive('settings') report?

    It is a check against the current route hierarchy, which makes it handy for highlighting parent menu items.
  3. 3. Why does a service that subscribes to routeDidChange in its constructor sometimes never run?

    The constructor runs on first lookup. If nothing reads the service, it is never built and never subscribes.
  4. 4. What is the practical benefit of the store keeping one record object per type and id?

    The identity map means all code shares one object per record, so state stays consistent across the app.

Summary

  • Inject router for navigation from code: transitionTo, replaceWith, isActive, urlFor, refresh, and the routeDidChange event.
  • Inject store for Ember Data; it keeps one cached record per type and id.
  • Addons add more services (page-title, intl, session) that you inject the same way.
  • Services are lazy, so anything that must run at boot has to be injected by something that does.

Next: Building Your Own App Services