wasAsked.

what are observable, subject and behaviour subject, how u can call them in angular?

EY · Role not specified · technical

Published

Year not specified · Angular

Community answers

Posted by wasAsked editorial collection

These are RxJS types that Angular uses heavily for asynchronous data. Observable - A stream of values over time that does nothing until someone subscribes. - Usually cold: each subscriber triggers its own execution. HttpClient.get returns a cold Observable, so subscribing twice sends two requests. this.http.get<User[]>('/api/users').subscribe(users => this.users = users); Subject - Both an Observable and an Observer: you can push values into it with next(), and many subscribers receive them (multicast, hot). - Subscribers only receive values emitted after they subscribe; there is no initial value. - Good for events: a "refresh requested" signal or a message bus between components. private refresh = new Subject<void>(); refresh$ = this.refresh.asObservable(); triggerRefresh() { this.refresh.next(); } BehaviorSubject - A Subject that requires an initial value and always holds the current value. - New subscribers immediately receive the latest value; you can also read it synchronously with getValue(). - Ideal for state in services: the current user, selected filters, cart contents. @Injectable({ providedIn: 'root' }) export class AuthStore { private readonly user = new BehaviorSubject<User | null>(null); readonly user$ = this.user.asObservable(); // expose read-only setUser(u: User | null) { this.user.next(u); } } // component user$ = inject(AuthStore).user$; // template: @if (user$ | async; as user) { Hello {{ user.name }} } Related types: ReplaySubject (replays the last N values to new subscribers) and AsyncSubject (emits only the final value on completion). Best practices - Keep Subjects private and expose asObservable() so only the service can emit. - Use the async pipe or takeUntilDestroyed to avoid leaks. - In modern Angular, signals often replace BehaviorSubject for synchronous state, while Observables remain best for async streams and events.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics