Bird
0
0

Consider this Angular service using the Observer pattern:

medium📝 state output Q13 of 15
Angular - Advanced Patterns
Consider this Angular service using the Observer pattern:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class DataService {
  private dataSubject = new Subject();
  data$ = this.dataSubject.asObservable();

  updateData(newData: string) {
    this.dataSubject.next(newData);
  }
}

What happens when updateData('Hello') is called?
AThe data is stored but not sent to subscribers.
BAll subscribers to <code>data$</code> receive the string 'Hello'.
CNothing happens until <code>subscribe()</code> is called inside <code>updateData</code>.
DThe service throws an error because Subject is private.
Step-by-Step Solution
Solution:
  1. Step 1: Understand Subject and Observable

    Subject allows emitting values to all subscribers via next().
  2. Step 2: Analyze updateData method

    Calling next('Hello') sends 'Hello' to all subscribers of data$ observable.
  3. Final Answer:

    All subscribers to data$ receive the string 'Hello'. -> Option B
  4. Quick Check:

    Subject.next() notifies subscribers [OK]
Quick Trick: Subject.next() sends data to all subscribers [OK]
Common Mistakes:
  • Confusing private property with access restrictions on next()
  • Thinking subscribe() must be inside updateData
  • Believing data is stored without notifying subscribers

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes