>

CODEMASTERYLAB

IDE PLATFORM
CoursesCommunity BlogsKnowledge GraphQuizzesInterview Prep

Sign in to track progress & earn XP

Sign In Create Account
>
Code Mastery Lab

Code Mastery Lab

Sign In

BehaviorSubject and State Streams — Services as Observable Data Sources

Question 1 / 1

0:00
Core
Medium

A NotificationService exposes a BehaviorSubject<Notification[]> initialised with an empty array. A ToastComponent subscribes to it in ngOnInit. Before ToastComponent initialises, the service emits two notification arrays. When ToastComponent subscribes, what does it receive?

typescript @Injectable({ providedIn: 'root' }) export class NotificationService { private notifications$ = new BehaviorSubject<Notification[]>([]);

getNotifications(): Observable<Notification[]> { return this.notifications$.asObservable(); }

push(notification: Notification): void { this.notifications$.next([...this.notifications$.getValue(), notification]); } }

// Before ToastComponent initialises: service.push({ message: 'First' }); // emits [{message:'First'}] service.push({ message: 'Second' }); // emits [{message:'First'},{message:'Second'}]

// ToastComponent subscribes now