Services and inject()

A service is a class for work that isn't about showing anything, such as calculations or calling an API. Mark it @Service(), and any component gets the one shared instance with inject(), like dependency injection in ASP.NET Core.

Apprentice · Angular · Updated

After this lesson you can

  • Create a service with @Service(), and get it in a component with inject()

Key takeaways

  • A service is a class for work that isn't about showing anything, such as working out prices or calling an API: components show, services work.
  • @Service() registers one shared instance for the whole app, a singleton like AddSingleton in ASP.NET Core. Older code writes @Injectable({ providedIn: 'root' }).
  • A component asks for a service with inject(), such as inject(PriceCalculator), and never creates it itself.
  • With the logic in one service, a change such as a new tax rate is made once, and every component that injects it sees the same data.

A component's job is to show things and react to the user. Work that isn't about the page, such as working out prices, keeping a cart, or calling your Web API, belongs somewhere else: in a service. It's the same split as in ASP.NET Core, where a controller handles the request and hands the real work to a DAO or a service.

Creating a service

ng generate service price-calculator
CREATE src/app/price-calculator.spec.ts
CREATE src/app/price-calculator.ts

Fill in price-calculator.ts:

import { Service } from '@angular/core';

@Service()
export class PriceCalculator {
  private readonly taxRate = 0.08;

  withTax(price: number): number {
    return Math.round(price * (1 + this.taxRate) * 100) / 100;
  }
}
  • @Service() marks the class as a service, and registers it for the whole app, with one instance shared by everyone who asks: a singleton, like AddSingleton in ASP.NET Core. Angular only creates it the first time someone asks.
  • In code written before Angular 22, you'll see the older way of saying the same thing: @Injectable({ providedIn: 'root' }). It still works, and means the same.

There's no template and no selector: a service never appears on the page.

Getting it with inject()

A component asks for a service with inject(), usually in a field:

import { Component, inject } from '@angular/core';
import { CurrencyPipe } from '@angular/common';
import { PriceCalculator } from './price-calculator';

@Component({
  imports: [CurrencyPipe],
  selector: 'app-price-tag',
  template: `<p>{{ price | currency }}, or {{ calculator.withTax(price) | currency }} with tax</p>`,
})
export class PriceTag {
  protected readonly calculator = inject(PriceCalculator);
  protected readonly price = 18;
}
$18.00, or $19.44 with tax

inject(PriceCalculator) asks Angular for the shared PriceCalculator, exactly like asking for an IProductDao in a controller's constructor: the component says what it needs, and doesn't create it. (A constructor parameter works too, constructor(private calculator: PriceCalculator) {}, but inject() is the modern style.)

Why bother?

  • One place for the logic. Every component that shows a price asks the same PriceCalculator. Change the tax rate once.
  • Small components. Components stay about the page; services hold the work.
  • Testable. A test can give a component a fake service, as your C# tests gave classes fake clocks.
  • Shared data. Because there's one instance, two components that inject the same service see the same data. That's the next two lessons.

Check yourself

1 question to try on the lesson page.

So what

Components show; services work. Write the work once in a @Service() class, and inject() it wherever it's needed: the same dependency injection you used in ASP.NET Core, now in the browser.

Key terms

Cheat sheets