Subscribe to variable change in Angular 4 Service



If you want to subscribe to variable change in Angular 4 service or Angular 5 service, you can use something called the BehaviorSubject from the rxjs library. A behavior subject is like an observable, except that it must be created with an initial value as it is must always return a value even if the subject hasn’t been updated. A behavior subject will always emit it’s first value as soon as it’s described. Here’s a confusing graph of how it works:

Anyway, you can use a behavior subject in an angular service to subscribe to variables changes in a service. Let’s build it with a simple example:

Angular Service

Say I have the following service that gets an array of people from a REST API call. I want to save this array as a behavior subject because the REST call can happen at any point in the program and I want a text field to show the size of the array at any given time.

Here are the relevant parts of my Angular service:

import { BehaviorSubject } from 'rxjs/BehaviorSubject';

private people: Array<Person>;

constructor( private http: Http) {
 this.people= new Array<Person>();
 this.observablePeople= new BehaviorSubject<Person[]>(this.people);
 }

In the above lines, I create a new behavior subject and provide my original array to it’s constructor.

eventChange() {
this.observablePeople.next(this.people);
}

Whenever you want to make changes to a behavior subject, you will need to call the next() function. In this case, I call next() with the people array, so I am overwriting the existing array with the new one that contains updated values.

getPeople() {
this.http.get(url, options).subscribe(res => {
let body = JSON.parse(res.text());
this.people= body;
this.eventChange();
})
}

Angular Component

Inside of the Angular component, here are the relevant parts:

import { Subscription } from 'rxjs/Subscription';

private subscription: Subscription;

public crowd: People[];

constructor(private alertService: AlertService) {
}

ngOnInit() {
this.subscription = this.alertService.observablePeople
.subscribe(item => {
this.crowd= item;
});

}

In the component, the subscribe event will get fired everytime next() is called on the bheavior subject. Since I am pushing a whole array with my next() function, the item that subscribe will receive will be a new array.

That’s all there is to it.