liveBook · Manning

BehaviorSubject

As explained in Modern Angular

BehaviorSubject is an RxJS subject that stores a current value, emits it to new subscribers, and multicasts subsequent values.

BehaviorSubject is an RxJS subject that holds a default and current value, lets multiple components subscribe to shared state, and propagates later changes. In Angular, a service can use it to represent authentication status or another changing application value. section 7.4.1 section 5.2

A practical Angular arrangement separates mutation from consumption:

  • Create the BehaviorSubject in a service with an initial value. section 3.2.2
  • Call next when an operation changes the represented state, such as successful login or logout. section 3.2.2
  • Expose an Observable with asObservable() so components can read the state without modifying the subject. section 3.2.2
  • Consume the exposed stream with Angular's async pipe or another subscription in a component. section 3.2.2

Authentication-aware footer

An AuthService initializes isAuth$ with false, changes it to true after login, and changes it back after logout. A shared isAuth() function injects AuthService and returns isAuth$.asObservable(). FooterComponent consumes that result in its template to conditionally render authentication-related content, without directly injecting the whole service. section 3.2.2

Listing 3.4 Showing user’s authentication status
import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject } from 'rxjs';
import { tap } from 'rxjs/operators';

@Injectable()
export class AuthService {
    private readonly http = inject(HttpClient);
    isAuth$ = new BehaviorSubject(false);  #1

    login(credentials: { email: string, password: string }) {
        return this.http.post('/api/auth/login', credentials).pipe(
            tap(() => this.isAuth$.next(true)),  #2
        );
    }

    logout() {
        return this.http.post('/api/auth/logout', {}).pipe(
            tap(() => this.isAuth$.next(false)) , #3
        );
    } 
}

Inspect the complete AuthService implementation, including initialization and login/logout updates. section 3.2.2

BehaviorSubject is especially useful for synchronous state that has a current value. During a migration to Angular signals, such subjects are candidates for conversion, while event-oriented or asynchronous streams require more care. section 7.4.1

How Modern Angular covers it

How deep it goes
Explains defaults, current values, multicasting, service encapsulation, component consumption, and migration toward signals.
Examples
Uses an authentication subject, login and logout updates, an injected accessor function, and an authentication-aware footer.
What it assumes
Assumes familiarity with Angular services, components, dependency injection, RxJS Observables, and subscriptions.
What you can do after
Apply BehaviorSubject to share mutable service state while exposing components an Observable-only read interface.
How it connects
Connects BehaviorSubject with RxJS, Observable, Angular services, signals, computed signals, effects, and state management.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern Angular. The section links point to the parts of the book it draws on.