How to subscribe to a variable in Angular 7
Let’s build a small Angular app with common header and footer , where we subscribe to a variable declared in a service and update a button in header according to the route of child component being loaded in DOM.
For example: If you have component A loaded, the header button should say “Load B” and vice-versa.
To make this happen, create a service called SharedVarService.
Declare a boolean variable called routerInfo of type RxJs BehaviorSubject and initialize it in a constructor.
import { Injectable } from '@angular/core';
import {BehaviorSubject, Observable} from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class SharedVarService {
private routerInfo: BehaviorSubject<boolean>;
constructor() {
this.routerInfo = new BehaviorSubject<boolean>(false);
}
}
Add a setValue method to set the variable value. Since a service can be injected into another components, you can set this variable’s value from anywhere you want by calling this setValue method.
setValue(newValue): void {
this.routerInfo.next(newValue);
}
Now create a getValue method to subscribe to the variable to retrieve the value when it gets updated.
getValue(): Observable<boolean> {
return this.routerInfo.asObservable();
}
Final Service class looks like this :
import { Injectable } from '@angular/core';
import {BehaviorSubject, Observable} from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class SharedVarService {
private routerInfo: BehaviorSubject<boolean>;
constructor() {
this.routerInfo = new BehaviorSubject<boolean>(false);
}
getValue(): Observable<boolean> {
return this.routerInfo.asObservable();
}
setValue(newValue): void {
this.routerInfo.next(newValue);
}
}
You can now inject this service in any component and get /set the variable value accordingly. In our case, let’s inject this service in Component B to set routerInfo value to true.
export class ChildBComponent implements OnInit {
constructor(private service: SharedVarService) { }
ngOnInit() {
this.service.setValue(true);
}
}
You can subscribe to the value of routerInfo by subscribing to the getValue() function in the service.
export class HeaderComponent implements OnInit {
public flag: boolean;
constructor(private service: SharedVarService) {
}
ngOnInit() {
this.service.getValue().subscribe((value) => {
this.flag = value;
});
}
}
Now use this flag to show/hide button in the html code.
You are all set!
Here’s the link to the app https://subscribetovar.stackblitz.io
You can access the source code here https://stackblitz.com/edit/subscribetovar