Video lecture
Watch on YouTube(opens in a new tab)Sub topic 13
Sharing Logic with Services and inject()
This chapter assumes you have already built a standalone component and can bind data in its template. You should also be comfortable with TypeScript classes and decorators.
Components should handle what the user sees. Logic that several components need, such as formatting, fetching data or keeping shared state, belongs in a service. A service is a plain TypeScript class. Angular creates it and hands it to the code that asks for it. That handoff is called dependency injection (DI).
The working model
DI involves three pieces:
| Piece | Role | Example |
|---|---|---|
| Token | Identifies what is requested | The `GreetingService` class |
| Provider | Tells Angular how to create it | `@Injectable({ providedIn: 'root' })` |
| Injector | Creates instances and caches them | The root injector built by `bootstrapApplication` |
When a component calls inject(GreetingService), Angular asks the nearest injector for that token. If that injector has no provider for it, the request moves up the tree until the root injector answers. With providedIn: 'root', the root injector creates a single instance the first time something asks for it. Every later request gets that same instance.
Writing and consuming a service
Generate a service with ng generate service greeting, or write it by hand:
import { Injectable, inject, Component } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class GreetingService {
greet(name: string): string {
return `Hello, ${name}!`;
}
}
@Component({
selector: 'app-greeting',
template: `<h1>{{ message }}</h1>`,
})
export class Greeting {
private greetingService = inject(GreetingService);
message = this.greetingService.greet('Angular');
}providedIn: 'root' registers the service app-wide and makes it tree-shakable: the build drops it if nothing injects it. The inject() function runs in a field initializer, which Angular treats as an injection context.
You may also see constructor injection, constructor(private greetingService: GreetingService) {}. It works the same way. inject() is the style the current docs recommend, because it works in functions and with inheritance and needs no constructor parameters.
Scoping a provider to a component
If you list a service in a component's providers array, that component and its children get their own instance:
@Component({
selector: 'app-greeting-panel',
providers: [GreetingService],
template: `<app-greeting />`,
imports: [Greeting],
})
export class GreetingPanel {}Each GreetingPanel creates a fresh GreetingService. Use this only when you need state isolated per component.
Common errors
- NG0203: inject() must be called from an injection context. You called
inject()inside a method, asetTimeoutcallback, or some other code that runs after construction. Move the call to a field initializer or the constructor. - NullInjectorError: No provider for X. The class has no
providedInand no provider is registered anywhere in the injector tree. AddprovidedIn: 'root'or list it inproviders. - Shared state isn't shared. The service also appears in a component's
providersarray, so that subtree gets a separate instance. Remove the extra provider. - Circular dependency (NG0200). Two services inject each other. Move the shared logic into a third service.
Exercise
Two sibling components both inject a CartService marked providedIn: 'root', but one of them also lists CartService in its own providers array. Items added in one component don't appear in the other. Why, and how do you fix it?
Show answer
The component with its own providers entry gets a separate CartService instance from its element injector, so the two siblings no longer share one singleton. Remove CartService from that component's providers array so both requests resolve to the root instance.
Exercise
A component method calls inject(GreetingService) when a button is clicked and throws NG0203. What should you change?
Show answer
inject() only works in an injection context, such as a field initializer or the constructor. Inject the service into a class field once, for example private greetingService = inject(GreetingService), and use that field inside the click handler.