Last active
July 26, 2018 17:14
-
-
Save robinraju/7cdfe6548e274883c74711e90aeec40e to your computer and use it in GitHub Desktop.
Detecting internet connectivity status inside angular application
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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