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
