Loading

Quipoin Menu

Learn • Practice • Grow

angular / Using Services for Data Sharing
interview

Q1. How can services be used to share data between components?
Services can hold shared state using RxJS subjects or BehaviorSubject. Components inject the service and subscribe to the data stream. One component updates the service, and others receive the updates. This is ideal for unrelated components that need to communicate.

Q2. What is BehaviorSubject and why use it?
BehaviorSubject is a type of RxJS Subject that requires an initial value and emits the current value to new subscribers. It''s perfect for shared state because it always provides the latest value. Example service:
private userSubject = new BehaviorSubject(null); user$ = this.userSubject.asObservable(); updateUser(user: User) { this.userSubject.next(user); }

Q3. How do components subscribe to service data?
Inject the service and subscribe to the observable. Example:
this.dataService.user$.subscribe(user => this.user = user);
Or use async pipe in template:
{{ dataService.user$ | async | json }}

Q4. What is the difference between Subject and BehaviorSubject?
Subject doesn''t require an initial value and only emits values after subscription. BehaviorSubject requires an initial value and always returns the last value to new subscribers. For shared state, BehaviorSubject is usually preferred because components can always get the current value.

Q5. How do you prevent memory leaks with subscriptions?
Always unsubscribe in ngOnDestroy. Use takeUntil pattern, or async pipe which handles unsubscription automatically. Example:
private destroy$ = new Subject(); this.service.data$.pipe(takeUntil(this.destroy$)).subscribe(); ngOnDestroy() { this.destroy$.next(); this.destroy$.complete(); }