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

inject()

Ask for a service.

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

Now the header, and the shelf, need the basket. They ask Angular for it, with inject.

  • Both need the basket
  • Ask Angular
  • inject

Using inject()

Inject, with a class, returns the instance Angular created. You call it in a class field. Every component that injects the basket gets the same object, so a change in one is seen by all.

keyvalue
basket = inject(Basket)ask for it
Wherea class field
Every componentthe same object
A changeseen by all

header.ts

Inject, with the class name, asks Angular for the basket. Angular gives back the one shared instance. The template reads the number of items.

header.tstypescript
import { Component, inject } from '@angular/core';
import { Basket } from './basket';

@Component({
  selector: 'app-header',
  template: `<h2>Basket: {{ basket.items().length }} books</h2>`,
})
export class Header {
  basket = inject(Basket);
}

A shared basket

The shelf injects the same basket. Each add button calls the service. And the last line lists the titles in the basket. We add Dune, and Circe. Run it. The header now says two books, because both components share one basket.

shelf.tstypescript
import { Component, inject } from '@angular/core';
import { Basket } from './basket';
import { BOOKS } from './books';

@Component({
  selector: 'app-shelf',
  template: `
    @for (b of books.slice(0, 3); track b.id) {
      <p>{{ b.title }} <button (click)="basket.add(b.title)">Add</button></p>
    }
    <p>In the basket: {{ basket.items().join(', ') }}</p>
  `,
})
export class Shelf {
  basket = inject(Basket);
  books = BOOKS;
}
Also uses header.ts
import { Component, inject } from '@angular/core';
import { Basket } from './basket';

@Component({
  selector: 'app-header',
  template: `<h2>Basket: {{ basket.items().length }} books</h2>`,
})
export class Header {
  basket = inject(Basket);
}
Also uses basket.ts
import { Service, signal } from '@angular/core';

@Service()
export class Basket {
  readonly items = signal<string[]>([]);

  add(title: string) {
    this.items.update(list => [...list, title]);
  }
}
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 books.ts
export interface Book {
  id: number;
  title: string;
  author: string;
  price: number;
  stock: number;
}

export const BOOKS: Book[] = [
  { id: 1, title: 'Dune', author: 'Frank Herbert', price: 9.99, stock: 4 },
  { id: 2, title: 'The Hobbit', author: 'J.R.R. Tolkien', price: 8.99, stock: 0 },
  { id: 3, title: 'Circe', author: 'Madeline Miller', price: 10.99, stock: 2 },
  { id: 4, title: 'Emma', author: 'Jane Austen', price: 6.99, stock: 7 },
  { id: 5, title: 'Persuasion', author: 'Jane Austen', price: 7.49, stock: 1 },
];
Also uses actions.json
[{"click": "p:nth-of-type(1) button"}, {"click": "p:nth-of-type(3) button"}]

inject() or the constructor?

Older code asks for services in the constructor. Inject does the same job, in a single line. New Angular code uses inject.

constructor(private b: Basket)

  • older stylein the constructorstill works

b = inject(Basket)

  • modern stylea class fieldrecommended

Summary

Inject asks Angular for a service, and every component gets the same instance. Next, the service decorator, and the older injectable decorator.

Key takeaways
  • inject(Basket)
  • Same instance
  • Shared state
Next up: @Service and @Injectable — two ways to declare