I am checking the Network Status in my Angular application from network.service.ts
// network.service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject } from "rxjs";
@Injectable()
export class NetworkStatusService {
public status: BehaviorSubject<any> = new BehaviorSubject<any>(null);
public appStatus() {
window.addEventListener('online', this.networkStatusChanged.bind(this));
window.addEventListener('offline', this.networkStatusChanged.bind(this));
}
public networkStatusChanged(): void {
this.status.next(!navigator.onLine);
}
}
In my component, I am injecting this service and in ngOnInit,
I am calling this appStatus method of the service and then subscribe to status (BehaviorSubject) to get the value.
In my component:
public ngOnInit() {
this.networkService.appStatus();
this.networkService.status.subscribe((x)=>{
console.log('status here', x);
if(x) {
// do something
}
});
}
This works and logs the boolean value whenever the application online/offline. But the problem is I would have to call this method and then subscribe & unsubscribe in pretty much every component. I know addEventListener does not return a value but is there a way to refactor this, so that I just call appStatus() from the component and it returns a boolean value (true/false) whenever the application is offline/online?
CodePudding user response:
You can just create a getter in any component where you want to call appStatus, it will return value of network status.
public get appStatus () {
return navigator.onLine
}
But if you need to listen every time BehaviorSubject emits value, u need to subscribe.
CodePudding user response:
Add your listeners inside service class constructor instead of appStatus() function. This way you don't have to call it every time or from every component.
import { Injectable } from '@angular/core';
import { BehaviorSubject } from "rxjs";
@Injectable()
export class NetworkStatusService {
public status: BehaviorSubject<any> = new BehaviorSubject<any>(null);
constructor() {
window.addEventListener('online', this.networkStatusChanged.bind(this));
window.addEventListener('offline', this.networkStatusChanged.bind(this));
}
public networkStatusChanged(): void {
this.status.next(!navigator.onLine);
}
}
Now subscribe this.networkService.status from any component as you are doing currently.