Consider this Angular component that uses a BehaviorSubject as a simple store. What will be displayed in the template after the button is clicked once?
import { Component } from '@angular/core'; import { BehaviorSubject } from 'rxjs'; @Component({ selector: 'app-counter', template: ` <p>Count: {{ count$ | async }}</p> <button (click)="increment()">Increment</button> ` }) export class CounterComponent { private countSubject = new BehaviorSubject<number>(0); count$ = this.countSubject.asObservable(); increment() { const current = this.countSubject.value; this.countSubject.next(current + 1); } }
Remember that BehaviorSubject holds the current value and emits it to subscribers immediately.
The BehaviorSubject starts with 0. When the button is clicked, increment() adds 1 and emits the new value. The template shows the updated count.
Given this code snippet, what is the final value emitted by store$?
import { BehaviorSubject } from 'rxjs'; const store = new BehaviorSubject({ count: 0 }); store.next({ count: store.value.count + 1 }); store.next({ count: store.value.count + 2 }); const store$ = store.asObservable();
Each next uses the current value at that moment.
First next adds 1 to 0 → 1. Second next adds 2 to 1 → 3. Final value is { count: 3 }.
Choose the correct code snippet that creates a BehaviorSubject with initial value 10 and exposes it as a read-only observable named value$.
Remember to use new keyword and specify initial value in constructor.
Option C correctly uses new BehaviorSubject and exposes value$ as observable. Others have syntax errors or wrong access modifiers.
In this Angular component, the template does not update when updateName is called. What is the cause?
import { Component } from '@angular/core'; import { BehaviorSubject } from 'rxjs'; @Component({ selector: 'app-name', template: ` <p>Name: {{ name$ | async }}</p> <button (click)="updateName('Alice')">Set Alice</button> ` }) export class NameComponent { private nameSubject = new BehaviorSubject<string>('Bob'); name$ = this.nameSubject.asObservable(); updateName(newName: string) { this.nameSubject.next(newName); } }
Check how to properly update a BehaviorSubject's value.
You must call next() to emit a new value. Assigning to value property does not trigger emission.
Choose the best explanation for why BehaviorSubject is often used as a simple store in Angular applications.
Think about how BehaviorSubject differs from a regular Subject.
BehaviorSubject keeps the latest value and emits it immediately to new subscribers, which is useful for state management and UI updates.