0
0
Angularframework~5 mins

Service-based state management in Angular

Choose your learning style9 modes available
Introduction

Service-based state management helps keep data shared and updated across parts of your app easily. It avoids repeating data and keeps everything in sync.

You want to share user login status across multiple components.
You need to keep a shopping cart updated in different pages.
You want to manage theme settings that affect many parts of the app.
You want to keep track of form data while moving between steps.
You want to avoid passing data through many component layers.
Syntax
Angular
import { Injectable, signal } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class StateService {
  private _count = signal(0);

  get count() {
    return this._count();
  }

  increment() {
    this._count.update(c => c + 1);
  }

  decrement() {
    this._count.update(c => c - 1);
  }
}

Use @Injectable({ providedIn: 'root' }) to make the service available app-wide.

Use Angular signals to hold and update state reactively.

Examples
This service holds a username and lets components get or set it.
Angular
import { Injectable, signal } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class UserService {
  private _username = signal('');

  get username() {
    return this._username();
  }

  setUsername(name: string) {
    this._username.set(name);
  }
}
This service manages a list of items in a shopping cart.
Angular
import { Injectable, signal } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class CartService {
  private _items = signal<string[]>([]);

  get items() {
    return this._items();
  }

  addItem(item: string) {
    this._items.update(items => [...items, item]);
  }

  clear() {
    this._items.set([]);
  }
}
Sample Program

This component shows a counter and buttons to change it. It uses the shared StateService to keep the count.

Angular
import { Component, inject } from '@angular/core';
import { StateService } from './state.service';

@Component({
  selector: 'app-counter',
  standalone: true,
  template: `
    <h2>Counter: {{ state.count }}</h2>
    <button (click)="state.increment()">+</button>
    <button (click)="state.decrement()">-</button>
  `
})
export class CounterComponent {
  state = inject(StateService);
}
OutputSuccess
Important Notes

Services are singletons by default, so all components share the same state instance.

Use Angular signals inside services for reactive updates that components can track.

Inject services using inject() or constructor injection in components.

Summary

Service-based state management shares data across components easily.

Angular signals inside services keep state reactive and simple.

Use @Injectable({ providedIn: 'root' }) to make services app-wide singletons.