Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 39 ยท Services and Dependency Injection

Services in Ember

Learn what Ember services are, how to generate and inject them, why they are lazy singletons, and when to use one instead of component or route state.

Components and routes in Ember come and go. A component is created when it appears on the screen and thrown away when it leaves. A route's state is tied to the page you are on. But some things must outlive any single screen: the signed-in user, a shopping cart, the current theme, a connection to a server. For these, Ember gives you services.

A service is a plain class that Ember creates once per application and hands to anyone who asks for it. Every component, route, helper and other service that injects cart receives the very same object. That makes a service the standard place for state and behavior that is shared across the app.

Real Ember vs stand-in. The code blocks marked with a file name are real Ember code and are read-only here, because the site cannot run the framework. The runnable examples are small stand-ins in plain JavaScript that model the same ideas (a registry that creates singletons on demand), so you can see the behavior without a build tool.

Generating a service

The Ember CLI creates the file, and a unit test for it, in one command:

Terminal
ember generate service shopping-cart

This makes app/services/shopping-cart.js. A service is just a class that extends Service. State that should trigger re-rendering is marked @tracked (more in Tracked Properties):

app/services/shopping-cart.js

JavaScript
import Service from '@ember/service';
import { tracked } from '@glimmer/tracking';

export default class ShoppingCartService extends Service {
  @tracked items = [];

  get count() {
    return this.items.length;
  }

  add(item) {
    this.items = [...this.items, item];
  }

  clear() {
    this.items = [];
  }
}

The file name decides the service's name. shopping-cart.js is registered as service:shopping-cart. Always use lowercase-dashed names for files; the class name inside is up to you.

Using a service

To use a service in a component, route, controller, helper or another service, inject it with the service decorator. The decorator creates a property that looks the service up when it is first read:

app/components/cart-badge.gjs

JavaScript
import Component from '@glimmer/component';
import { service } from '@ember/service';

export default class CartBadge extends Component {
  @service shoppingCart;

  <template>
    <span class="badge">{{this.shoppingCart.count}}</span>
  </template>
}

Here the property name shoppingCart is the camelCase form of the file name shopping-cart, so Ember finds service:shopping-cart without being told. If you want a different property name, pass the service name to the decorator:

JavaScript
@service('shopping-cart') cart;

Because the cart is @tracked, the badge updates by itself the moment any other part of the app calls cart.add(...). Nobody has to notify the badge.

Lazy singletons

Two facts define how services behave.

  1. Singleton. There is one instance for the whole application (strictly: one per application instance, which matters in tests, where every test gets its own fresh app and therefore its own fresh services).
  2. Lazy. The instance is created the first time somebody asks for it, not when the app boots. If no code ever reads this.cart, the cart service is never built.

Both are easy to see in a tiny stand-in. The Container below registers classes by name and creates an instance only on the first lookup.

JS Stand-in: lazy singletons

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

No output.

The constructor message appears exactly once even though we looked the service up twice. That is the whole trick: Ember keeps a registry of classes and a cache of the instances it has built.

Sharing state between distant parts of the app

The main reason to reach for a service is that two parts of the page that are not parent and child need the same data. A product list adds items; a header badge shows the count; a checkout page lists them. Passing the cart through every component in between would be tedious. With a service, each part just injects it.

flowchart LR
  A["ProductList component"] -->|add| S(("shopping-cart service"))
  B["CartBadge component"] -->|reads count| S
  C["Checkout route"] -->|reads items| S

Three unrelated parts of the app share one service instance.

The next stand-in plays that story. Each "component" is a function that receives the cart; because all of them get the same instance, one change is visible everywhere. A tiny render function stands in for Ember's template updates.

JS Stand-in: one cart, three consumers

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

No output.

When to use a service (and when not to)

Services are powerful, which makes them easy to overuse. A quick guide:

Situation Better home
A toggle that only one component cares about a @tracked property on that component
Data that belongs to one page and is loaded for it the route's model hook
Data needed by a parent and its child pass it down as an argument
The signed-in user, cart, theme, notifications, a websocket a service
Logic used in many places (formatting, API calls, analytics) a service or a plain utility function

A service is global to the app, so everything stored in it lives until the user closes the tab (or you clear it). Keep services small and focused: one session, one cart, one notifications, not one giant app-state.

If a function has no state and no need for the app (no injected services), it does not need to be a service. A plain exported function in app/utils/ is simpler to write and to test.

Services can use other services

A service may inject other services with the same @service decorator. Lazy creation means that order does not matter and cycles are not a problem at load time, so a checkout service can freely use cart and session. The next lesson explains how Ember finds these dependencies.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How many instances of a service does an Ember application normally create?

    Services are lazy singletons. The first lookup creates the instance and every later injection receives the same object.
  2. 2. A file is named app/services/user-settings.js. Which property injects it under the default name?

    The dasherized file name maps to camelCase for the property, so user-settings becomes userSettings. You can also write @service('user-settings') anyName.
  3. 3. Which piece of state is the best candidate for a service?

    The cart is needed by unrelated parts of the app and must survive navigation, which is exactly what a service is for. The others are local to one component or method.
  4. 4. When is a service instance created?

    Injection is lazy. If nothing ever reads the service, it is never constructed.

Summary

  • A service is a class extending Service in app/services/, created once per application and shared by everything that injects it.
  • Inject with @service name; or @service('dashed-name') anyName;.
  • Instances are lazy: built on first use, then cached.
  • Use services for app-wide, long-lived state and behavior; keep local state in components and page state in routes.
  • Mark service fields @tracked so that anything that reads them re-renders when they change.

Next: Dependency Injection and the Owner