Today I had to implement an observable in one project in angular, and I found that BehaviorSubject was the best option, so first let's define BehaviorSubject, is a type of subject, a subject is a special type of observable (is a producer of multiple values, "pushing" them to observers or consumers who are subscribed to that producer) so you can subscribe to messages like any other observable. The unique features of BehaviorSubject are:
- It needs an initial value as it must always return a value on subscription even if it hasn't received a next()
- Upon subscription, it returns the last value of the subject.
- At any point, you can retrieve the last value of the subject in a non-observable code using the getValue() method.
With that in mind lets go to see the little example.
componentService.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable()
export class ComponentService {
public dataObsevable: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(null);
constructor() {
}
onDataReceived = (close: boolean) => this.dataObsevable.next(close);
}
component.ts
import { OnInit } from '@angular/core';
import { ComponentService } from '../../componentService.ts';
export class Component implements OnInit {
public dataObsevable: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(null);
constructor(
private componentService: ComponentService
) { }
/* Is important to always call the method to subscribe in the ngOnInit or constructor */
ngOnInit() {
this.onDataChangeReceived();
}
onDataChangeReceived = () => {
this.componentService.onDataReceived.subscribe((change: boolean) => {
if (change) {
/*Something*/
}
});
}
}
I hope this will be helpful for all of you and thanks for reading!!
Top comments (1)
What is the use of
dataObsevable
property oncomponent.ts
file ?I think it should be removed from there.