Angular Dependency Injection
Angular resolves an injection token through the active injector hierarchy. Repeated requests for the same provider in the same scope normally receive the same instance.
How it works
The component injects DeskCounter twice and increments it through one reference. Reading through the other reveals the shared instance in this scope. The provider belongs to the component, so a separate component instance can receive a separate counter. This distinction is useful for screen-local workflows that should not leak state into a different screen.
Run the code
Use a separate empty project folder with a compatible Node version: ^22.22.3, ^24.15.0 or a supported 26+ runtime. The review uses Node 24.22.1, Angular 22.2.4, CLI/build 22.2.5 and TypeScript 6.0.3. Node 22.15.1 is too old for Angular 22. Save every download at its displayed path; browsers may keep only the basename, so recreate the src folder. Run npm install, npm run build and npm start, then open the loopback address printed by the server. Run npm test for the supplied component tests. These are local teaching projects, not Bhylu publishing files.
The small loopback server serves the compiled app and fixed, read-only tool API fixtures. It is not a database, authentication or lending service. Angular examples do not run in Bhylu’s current HTML or TypeScript playground. No Apache, MySQL or PHP configuration change is needed.
Example
import { Component } from '@angular/core';
import { Injectable, inject, signal } from '@angular/core';
@Injectable()
class DeskCounter {
count = signal(0);
}
@Component({
selector: 'bh-dependency-injection',
standalone: true,
imports: [],
template: `<button type="button" (click)="first.count.update(add)">Count visit</button>
<p data-result>{{ second.count() }} visits</p>`,
providers: [DeskCounter],
})
export class App {
first = inject(DeskCounter);
second = inject(DeskCounter);
add = (value: number) => value + 1;
}
Expected result
0 visits
The click produces one visit through the second reference as well. A missing provider is a configuration error, not a reason to instantiate an unrelated fallback silently. Optional injection is appropriate only when absence is part of the declared contract.