Skip to content

Instantly share code, notes, and snippets.

@robinraju
Last active July 26, 2018 17:14
Show Gist options
  • Save robinraju/7cdfe6548e274883c74711e90aeec40e to your computer and use it in GitHub Desktop.
Save robinraju/7cdfe6548e274883c74711e90aeec40e to your computer and use it in GitHub Desktop.
Detecting internet connectivity status inside angular application
import {Component, OnDestroy, OnInit} from '@angular/core';
import {fromEvent, Observable, Subscription} from 'rxjs';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnDestroy {
onlineEvent: Observable<Event>;
offlineEvent: Observable<Event>;
subscriptions: Subscription[] = [];
connectionStatusMessage: string;
connectionStatus: string;
constructor() {}
ngOnInit(): void {
/**
* Get the online/offline status from browser window
*/
this.onlineEvent = fromEvent(window, 'online');
this.offlineEvent = fromEvent(window, 'offline');
this.subscriptions.push(this.onlineEvent.subscribe(e => {
this.connectionStatusMessage = 'Back to online';
this.connectionStatus = 'online';
console.log('Online...');
}));
this.subscriptions.push(this.offlineEvent.subscribe(e => {
this.connectionStatusMessage = 'Connection lost! You are not connected to internet';
this.connectionStatus = 'offline';
console.log('Offline...');
}));
}
ngOnDestroy(): void {
/**
* Unsubscribe all subscriptions to avoid memory leak
*/
this.subscriptions.forEach(subscription => subscription.unsubscribe());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment