AI Hints
Home›Angular Tutorial›Why Services, Creating a Service and inject()
Angular · Lesson 64 of 120

Why Services

Share code and data.

⏱ 2 min read▶ Video at 1:15:38🎓 Free
Watch this lesson in the Angular courseWatch on YouTube ↗Full Angular course

The header shows the basket count. The shelf has the add buttons. They're different components, but they need the same basket.

  • The header shows the count
  • The shelf adds books
  • One basket for both

Two separate counts

The shelf has its own count, and adds one on each click. The header has a different count, of its own. We click add twice. Run it. The shelf counted two, but the header still says zero. The two components can't see each other's data.

shelf.tstypescript
import { Component, signal } from '@angular/core';

@Component({
  selector: 'app-shelf',
  template: `
    <p>Dune <button (click)="count.update(c => c + 1)">Add</button></p>
    <p>The shelf counted {{ count() }}.</p>
  `,
})
export class Shelf {
  count = signal(0);
}
Also uses header.ts
import { Component, signal } from '@angular/core';

@Component({
  selector: 'app-header',
  template: `<h2>Basket: {{ count() }} books</h2>`,
})
export class Header {
  count = signal(0);
}
Also uses app.ts
import { Component } from '@angular/core';
import { Header } from './header';
import { Shelf } from './shelf';

@Component({
  selector: 'app-root',
  imports: [Header, Shelf],
  template: `<app-header /><app-shelf />`,
})
export class App {}
Also uses actions.json
[{"click": "button", "times": 2}]

What a service is

A service is a plain class, that holds data, or logic, that many components need. Angular creates it, and hands the same instance to every component that asks. So the header, and the shelf, can share one basket.

keyvalue
A servicea plain class
Holdsshared data and logic
Angularcreates it for you
Every componentgets the same one

Components and a service

Components focus on showing things, and handling clicks. The service keeps the data, and the rules. Components ask Angular for the service, and Angular gives them the shared instance.

  1. Components: show and click
  2. Service: data and rules
  3. Ask Angular for it
  4. Same instance everywhere

Summary

Components can't see each other's data. A service holds shared data, and Angular gives every component the same one. Next, creating a service.

Key takeaways
  • Separate state
  • A shared service
  • One instance
Next up: Creating a Service — @Service