Bird
0
0

You want to create a simple store using BehaviorSubject to hold a user's profile object and update it safely. Which approach correctly updates only the user's name without losing other profile data?

hard📝 Application Q15 of 15
Angular - State Management
You want to create a simple store using BehaviorSubject to hold a user's profile object and update it safely. Which approach correctly updates only the user's name without losing other profile data?
const profile$ = new BehaviorSubject({ name: 'Alice', age: 30 });
// Update name to 'Bob' here
Aprofile$.next({ ...profile$.value, name: 'Bob' });
Bprofile$.next({ name: 'Bob' });
Cprofile$.value.name = 'Bob';
Dprofile$.update({ name: 'Bob' });
Step-by-Step Solution
Solution:
  1. Step 1: Understand BehaviorSubject value update

    Directly assigning to value property does not notify subscribers; next() must be called with full updated object.
  2. Step 2: Preserve existing data while updating name

    Use spread operator to copy existing profile and override name, then call next() with new object.
  3. Step 3: Check other options

    profile$.next({ name: 'Bob' }); loses age property; profile$.value.name = 'Bob'; mutates value without notification; profile$.update({ name: 'Bob' }); uses non-existent update() method.
  4. Final Answer:

    profile$.next({ ...profile$.value, name: 'Bob' }); -> Option A
  5. Quick Check:

    Use next() with spread to update partial data [OK]
Quick Trick: Use spread operator with next() to update partial store data [OK]
Common Mistakes:
  • Overwriting entire object losing other properties
  • Mutating value directly without next()
  • Using non-existent update() method

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes