AI Hints
Home›Angular Tutorial›Providers, Injection Tokens and Practice: A Wishlist Service
Angular · Lesson 70 of 120

Providers

Where services come from.

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

So far, every service has been shared by the whole app. But sometimes, each component needs its own copy. Like a counter, inside each box.

  • Shared by the whole app
  • Sometimes, one each
  • Providers

What a provider is

A provider tells Angular how to create something, and where. Auto provided services live at the root, with one for the whole app. A component's providers list creates a new instance, just for that component, and its children.

keyvalue
Rootone for the whole app
providers: [Counter]one per component
Childrenshare their parent's one
app.config.tsapp-wide providers

counter.ts

Auto provided, false, means Angular won't create a counter on its own. Someone has to provide it. The counter keeps a value, and up adds one.

counter.tstypescript
import { Service, signal } from '@angular/core';

@Service({ autoProvided: false })
export class Counter {
  readonly value = signal(0);

  up() {
    this.value.update(v => v + 1);
  }
}

One counter per box

The box lists counter in its providers. So every box gets a new counter, of its own. We click the first box three times, and the second box once. Run it. The first counts three, and the second counts one. Each box has its own counter.

box.tstypescript
import { Component, inject } from '@angular/core';
import { Counter } from './counter';

@Component({
  selector: 'app-box',
  providers: [Counter],
  template: `<p class="card">Count: {{ counter.value() }}
    <button (click)="counter.up()">+1</button></p>`,
})
export class Box {
  counter = inject(Counter);
}
Also uses counter.ts
import { Service, signal } from '@angular/core';

@Service({ autoProvided: false })
export class Counter {
  readonly value = signal(0);

  up() {
    this.value.update(v => v + 1);
  }
}
Also uses app.ts
import { Component } from '@angular/core';
import { Box } from './box';

@Component({
  selector: 'app-root',
  imports: [Box],
  template: `<app-box /><app-box />`,
})
export class App {}
Also uses actions.json
[{"click": "app-box:nth-of-type(1) button", "times": 3}, {"click": "app-box:nth-of-type(2) button"}]

Summary

Root services are shared by the whole app. A component's providers list gives each component its own instance. Next, injection tokens.

Key takeaways
  • Root: one for all
  • providers: [ ]
  • One per component
Next up: Injection Tokens — inject plain values