Subjects — Complete Guide
Subjects — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of MEAN Stack Tutorial on Toolliyo Academy.
On this page
MEAN Stack Tutorial · Lesson 27 of 100
Subjects
Stack → Projects
Stack · 1 — Pieces · ~6 min · MEAN — TypeScript & RxJS
What is this?
Subjects are special Observables that multicast — you push values with .next(). BehaviorSubject remembers the latest value for MeanVerse shared UI state.
Why should you care?
Multiple components need the same current user or theme; Subject bridges imperative code and Observable templates.
See it live — copy this example
Paste into your MeanVerse project (Angular + Express + MongoDB), then run with ng serve / node / mongosh as noted.
@Injectable({ providedIn: 'root' })
export class AuthStore {
private userSubject = new BehaviorSubject<User | null>(null);
user$ = this.userSubject.asObservable();
setUser(user: User | null): void {
this.userSubject.next(user);
}
snapshot(): User | null {
return this.userSubject.getValue();
}
}
What happened?
- BehaviorSubject starts with null.
- asObservable() hides next() from consumers — they only subscribe.
- getValue() reads current user synchronously for guards.
Practice next
- Create BehaviorSubject for selected account id.
- Expose read-only user$ without exposing subject.
- Call setUser after login API succeeds.
- Replace BehaviorSubject with toObservable(signal) in new code.
- Use ReplaySubject(1) for last API error message.
Remember
Subject = Observable you write to. BehaviorSubject stores latest value. Hide subject; expose Observable API.
Session broadcast
Logout in header must clear dashboard and sidebar instantly.
Outcome: AuthStore.next(null) updates all subscribers together.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!