How to implement behavior subject using service in Angular 8

I’m going to show you a simple way: @Injectable() export class ProfileService { private profileObs$: BehaviorSubject<Profile> = new BehaviorSubject(null); getProfileObs(): Observable<Profile> { return this.profileObs$.asObservable(); } setProfileObs(profile: Profile) { this.profileObs$.next(profile); } } Now when you update something anywhere in the application, you can set that change by the ProfileService and each subscriber is receiving the change. … Read more

What is the difference between BehaviorSubject and Observable?

BehaviorSubject is a variant of Subject, a type of Observable to which one can “subscribe” like any other Observable. Features of BehaviorSubject It needs an initial value as it must always return a value upon subscription, even if it has not received the method next() Upon subscription, it returns the last value of the Subject. … Read more

What is the difference between Subject and BehaviorSubject?

A BehaviorSubject holds one value. When it is subscribed it emits the value immediately. A Subject doesn’t hold a value. Subject example (with RxJS 5 API): const subject = new Rx.Subject(); subject.next(1); subject.subscribe(x => console.log(x)); Console output will be empty BehaviorSubject example: const subject = new Rx.BehaviorSubject(0); subject.next(1); subject.subscribe(x => console.log(x)); Console output: 1 In … Read more