Sub topic 13
Sharing Logic with Services and inject()
Components should focus on what the user sees and does. Some code doesn't belong to any one view: fetching data, holding a shopping cart, formatting values the same way everywhere, or logging. Angular puts that code in services and hands them to components through dependency injection (DI).
This chapter assumes you have read the earlier chapters on standalone components and signals. You should be comfortable with @Component, signal(), computed(), and TypeScript classes and decorators.
What a Service Is
In Angular, a service is an ordinary TypeScript class with a narrow, well-defined job. The framework does not require a base class or a special interface. The class becomes injectable when you mark it with @Injectable and tell Angular where to provide it.
Dependency injection is a pattern where a class asks for what it needs instead of creating it. A component never writes new GreetingService(). It asks Angular for a GreetingService, and Angular returns an instance it manages. That gives you three benefits:
- Sharing. Many components can receive the same instance, so they share state.
- Replaceability. Tests or different environments can provide a substitute class without changing the consumer.
- Lifetime control. Angular decides when the instance is created and destroyed, based on where it is provided.
A Minimal Service and inject()
Here is the smallest useful example. The service is registered with the root injector, and a component pulls it in with the inject() function.
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');
}The CLI can scaffold the service file for you:
ng generate service greetingprovidedIn: 'root' means "make one instance for the whole application, created the first time someone asks for it." If no code ever injects the service, the build tool can drop it from the bundle (this is called tree-shaking). For most services, this is the right default.
inject() versus constructor injection
Older Angular code and many tutorials declare dependencies as constructor parameters:
import { Component } from '@angular/core';
import { GreetingService } from './greeting.service';
@Component({
selector: 'app-greeting-legacy',
template: `<h1>{{ message }}</h1>`,
})
export class GreetingLegacy {
message: string;
constructor(private greetingService: GreetingService) {
this.message = this.greetingService.greet('Angular');
}
}Both styles resolve the same provider. Current Angular documentation and CLI schematics prefer inject() for these reasons:
| Concern | `inject()` | Constructor parameters |
|---|---|---|
| Works in field initializers | Yes | No, fields that need the dependency must wait for the constructor |
| Inheritance | Subclasses don't re-declare parent dependencies | Subclasses must pass every dependency to `super()` |
| Usable in plain functions (guards, interceptors, factories) | Yes | No |
| Relies on TypeScript emitting decorator metadata | No | Yes, through Angular's compiler |
Sharing State Through a Service
A service becomes more useful when it holds state that several components read. Signals fit well here. The service owns a writable signal, exposes it read-only, and offers methods that make the only allowed changes.
// src/app/cart.service.ts
import { Injectable, computed, signal } from '@angular/core';
export interface CartItem {
id: number;
name: string;
price: number;
}
@Injectable({ providedIn: 'root' })
export class CartService {
private readonly items = signal<CartItem[]>([]);
readonly allItems = this.items.asReadonly();
readonly count = computed(() => this.items().length);
readonly total = computed(() =>
this.items().reduce((sum, item) => sum + item.price, 0)
);
add(item: CartItem): void {
this.items.update((list) => [...list, item]);
}
clear(): void {
this.items.set([]);
}
}Two unrelated components can now cooperate without passing inputs and outputs through every component between them:
// src/app/product-card.ts
import { Component, inject, input } from '@angular/core';
import { CartService, CartItem } from './cart.service';
@Component({
selector: 'app-product-card',
template: `
<h3>{{ product().name }}</h3>
<button (click)="cart.add(product())">Add to cart</button>
`,
})
export class ProductCard {
product = input.required<CartItem>();
protected cart = inject(CartService);
}// src/app/cart-summary.ts
import { Component, inject } from '@angular/core';
import { CurrencyPipe } from '@angular/common';
import { CartService } from './cart.service';
@Component({
selector: 'app-cart-summary',
imports: [CurrencyPipe],
template: `
<p>{{ cart.count() }} items, {{ cart.total() | currency }}</p>
<button (click)="cart.clear()">Clear</button>
`,
})
export class CartSummary {
protected cart = inject(CartService);
}Clicking "Add to cart" in any ProductCard updates the summary right away, because both components hold the same CartService instance and the template reads its signals.
How Angular Finds a Provider
Every request to inject() is resolved by an injector. Injectors form a hierarchy. Angular searches from the requesting component upward and stops at the first injector that has a provider for the token.
The level you provide a service at sets how many instances exist:
| Where it is provided | Instances | Typical use |
|---|---|---|
| `@Injectable({ providedIn: 'root' })` | One for the app | Shared state, API clients, logging |
| `providers` in `appConfig` | One for the app | Configuration values, third-party setup functions like `provideRouter` |
| `providers` on a route | One per lazily loaded route subtree | Feature-scoped state |
| `providers` in `@Component` | One per component instance, shared with its children | State that must reset for each widget |
Component-level providers
Sometimes you want a fresh instance for each component, for example a form wizard that keeps its own step state. List the service in the component's providers array:
import { Component, Injectable, inject, signal } from '@angular/core';
@Injectable()
export class WizardState {
step = signal(1);
next() {
this.step.update((s) => s + 1);
}
}
@Component({
selector: 'app-wizard',
providers: [WizardState],
template: `
<p>Step {{ state.step() }}</p>
<button (click)="state.next()">Next</button>
`,
})
export class Wizard {
protected state = inject(WizardState);
}Two <app-wizard> elements on the page each get their own WizardState, and each instance is destroyed with its component. WizardState has no providedIn, so it can only be injected where a providers array lists it.
Injecting Values That Aren't Classes
A class works as its own lookup key. A string, number, or configuration object has no class to use as a key, so you create an InjectionToken:
// src/app/api-url.token.ts
import { InjectionToken } from '@angular/core';
export const API_URL = new InjectionToken<string>('API_URL');// src/app/app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { API_URL } from './api-url.token';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes),
{ provide: API_URL, useValue: 'https://api.example.com' },
],
};Any service or component can then call inject(API_URL) and receive a typed string. The same provide syntax supports useClass (substitute another class), useFactory (compute the value), and useExisting (alias one token to another). Tests use these to swap in fakes.
Common Errors
NG0203: inject() must be called from an injection context
inject() only works while Angular is creating something: during field initializers, in a constructor, or inside a provider factory, route guard, or interceptor function. Calling it later fails:
import { Component, inject } from '@angular/core';
import { CartService } from './cart.service';
@Component({ selector: 'app-broken', template: `<button (click)="load()">Load</button>` })
export class Broken {
load() {
const cart = inject(CartService); // Throws NG0203 at click time
cart.clear();
}
}The fix is to inject in a field and use the field later. If you really need to resolve something lazily, inject Injector in a field and call injector.get(CartService) or runInInjectionContext(injector, () => ...).
NullInjectorError: No provider for X
Angular searched the whole hierarchy and found nothing. Usual causes:
- The service has
@Injectable()with noprovidedIn, and noprovidersarray lists it. - A provider function such as
provideHttpClient()is missing fromappConfig, soHttpClientcannot be injected. - The service is provided on one component but injected from a sibling that is not below it in the tree.
Unexpected multiple instances
If a component's state "doesn't sync," check whether a providedIn: 'root' service is also listed in some component's providers. That component and its children receive a separate instance that shadows the root one.
Circular dependencies
If AService injects BService and BService injects AService, Angular throws NG0200. Move the shared logic into a third service, or have one side inject Injector and resolve the other lazily.
Exercise
You render three <app-counter-panel> components. Each injects CounterService and they all show the same number, but you want each panel to count independently. What is the smallest change that fixes this, and what happens to each counter when its panel is removed?
Show answer
Add providers: [CounterService] to the CounterPanel component's decorator (and remove providedIn: 'root' if it shouldn't be shared anywhere). Each panel then gets its own instance from its element injector. That instance is destroyed with its panel, so its count is discarded.
Exercise
A component calls inject(LoggerService) inside ngOnInit() and the app throws NG0203. Explain why and rewrite the dependency correctly.
Show answer
ngOnInit runs after construction, outside an injection context, so inject() is not allowed there. Move the call to a field initializer, for example private logger = inject(LoggerService);, and use this.logger inside ngOnInit.
Exercise
Create an InjectionToken named MAXCARTITEMS with type number, provide the value 10 in appConfig, and use it in CartService so that add() ignores items once the limit is reached.
Show answer
Define export const MAX_CART_ITEMS = new InjectionToken<number>('MAX_CART_ITEMS');. Add { provide: MAX_CART_ITEMS, useValue: 10 } to the providers in appConfig. In CartService, add the field private readonly max = inject(MAX_CART_ITEMS); and start add() with if (this.items().length >= this.max) return; before calling update.