Chuyển đến nội dung

Bài 25 · Services and Dependency Injection

Building Your Own App Services

Design real Ember services: an authentication session, a notification queue and a persisted settings service, with patterns for async work, cleanup and testing.

You now know what a service is and how Ember finds one. This lesson is about designing good ones. We will build the three services almost every real app needs: a session (who is signed in), a notifications queue (messages that appear and disappear) and a settings service (preferences that survive a reload). Along the way you will see patterns for async work, cleanup and keeping a service easy to test.

Real Ember vs stand-in. The file-named blocks are real Ember code, shown read-only. The runnable blocks are plain-JavaScript versions of the same logic, so you can run and change them here.

Design rules for a good service

  • One job. session knows about authentication, not about shopping.
  • A small public API. A few methods and tracked fields; keep the helpers private (#name).
  • State is tracked, logic is plain. Anything templates display is @tracked; the rest is normal code.
  • No DOM. A service should not reach into the page. Components own the DOM; the service owns the data.
  • Easy to fake. Depend on other services, not on fetch calls hidden deep inside; then a test can register a fake.

A session service

The session remembers the current user and exposes login and logout. It also decides what to do after signing in, so components do not each re-implement that.

app/services/session.js

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

export default class SessionService extends Service {
  @service router;

  @tracked user = null;
  @tracked error = null;

  get isAuthenticated() {
    return this.user !== null;
  }

  async login(email, password) {
    this.error = null;
    const response = await fetch('/api/session', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email, password }),
    });
    if (!response.ok) {
      this.error = 'Wrong email or password';
      return false;
    }
    this.user = await response.json();
    this.router.transitionTo('dashboard');
    return true;
  }

  logout() {
    this.user = null;
    this.router.transitionTo('login');
  }
}

A route can then guard itself by asking the session:

app/routes/dashboard.js

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

export default class DashboardRoute extends Route {
  @service session;
  @service router;

  beforeModel() {
    if (!this.session.isAuthenticated) {
      this.router.replaceWith('login');
    }
  }
}

Any template that reads {{this.session.user.name}} or {{this.session.isAuthenticated}} updates the moment the service changes.

Never keep secrets in a service and assume they are safe: all JavaScript runs on the user's machine. A session service holds state (who the server says is signed in). The real protection is the server refusing unauthorized requests.

A notifications service

A notification queue is a perfect service: any part of the app can say "show this message", and one component renders the queue. It adds a message and removes it automatically after a timeout.

app/services/notifications.js

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

export default class NotificationsService extends Service {
  @tracked messages = [];
  #nextId = 1;
  #timers = new Set();

  constructor() {
    super(...arguments);
    registerDestructor(this, () => this.#timers.forEach(clearTimeout));
  }

  add(text, { kind = 'info', timeout = 4000 } = {}) {
    const message = { id: this.#nextId++, text, kind };
    this.messages = [...this.messages, message];
    if (timeout > 0) {
      const timer = setTimeout(() => this.dismiss(message.id), timeout);
      this.#timers.add(timer);
    }
    return message.id;
  }

  dismiss(id) {
    this.messages = this.messages.filter((message) => message.id !== id);
  }
}

Two details matter. First, this.messages is replaced with a new array rather than mutated with push; that is the simplest way to make Ember notice the change (see Tracked Properties). Second, timers are cleaned up in a destructor, so tests and fast navigation do not leave stray callbacks running after the service is gone.

The runnable stand-in below keeps the same logic and uses a fake clock so the output is deterministic. Notice how the timers are injected as a parameter: that is the "easy to fake" rule at work.

JS Stand-in: a notifications queue with a fake clock

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

No output.

A settings service that persists

Preferences such as the theme or language should survive a reload. A service can read from localStorage once, when it is created, and write whenever a value changes.

app/services/settings.js

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

const KEY = 'app-settings';

export default class SettingsService extends Service {
  @tracked theme = 'light';
  @tracked language = 'en';

  constructor() {
    super(...arguments);
    try {
      const saved = JSON.parse(localStorage.getItem(KEY) ?? '{}');
      this.theme = saved.theme ?? this.theme;
      this.language = saved.language ?? this.language;
    } catch {
      // private mode or corrupt data: keep the defaults
    }
  }

  update(changes) {
    Object.assign(this, changes);
    try {
      localStorage.setItem(KEY, JSON.stringify({ theme: this.theme, language: this.language }));
    } catch {
      // storage can be unavailable; the app still works
    }
  }
}

Always wrap storage access in try/catch: it throws in private browsing modes and when storage is full. In the stand-in below, the storage is a parameter, so we can use a plain object and watch what gets saved.

JS Stand-in: persisted settings

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

No output.

Using the services together

A save button might do three things: call the server, show a message, and redirect. Each belongs to a different service, and the component only coordinates:

JavaScript
@service notifications;
@service router;

@action
async save() {
  try {
    await this.args.post.save();
    this.notifications.add('Post saved');
    this.router.transitionTo('posts.post', this.args.post.id);
  } catch {
    this.notifications.add('Could not save the post', { kind: 'error' });
  }
}

The component stays short because the shared behavior lives in services. Testing it is easy too: register a fake notifications service in the test and assert that add was called.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Why does the notifications service replace this.messages with a new array instead of using push?

    Tracked properties notice assignments. Mutating the same array in place does not trigger an update unless it is a tracked collection.
  2. 2. What is a destructor (registerDestructor) used for in a service?

    Destructors run when Ember destroys the object, which is the right place to clear timers, listeners and subscriptions.
  3. 3. Why wrap localStorage access in try/catch inside a settings service?

    Storage is an environment feature that can be missing or broken. Falling back to defaults keeps the app usable.
  4. 4. Which design makes a service easiest to test?

    When dependencies come from the owner (or constructor arguments), a test controls them without touching the real network, clock or storage.

Summary

  • Keep services focused: session, notifications, settings, not one catch-all.
  • Put displayed state in @tracked fields and replace arrays/objects instead of mutating them.
  • Clean up timers and listeners with registerDestructor.
  • Guard browser storage with try/catch and fall back to defaults.
  • Let components coordinate services; let services own the data and rules.

Next: Tracked Properties

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.