Skip to content

Instantly share code, notes, and snippets.

@mohamedaboelmagd
Created March 26, 2019 12:58
Show Gist options
  • Save mohamedaboelmagd/0c876bf41c100360b57401ac2e59e5cb to your computer and use it in GitHub Desktop.
Save mohamedaboelmagd/0c876bf41c100360b57401ac2e59e5cb to your computer and use it in GitHub Desktop.
Check user has internet connection or not using Angular 2
export class ExtendedHttpService extends Http {
constructor(backend: XHRBackend, defaultOptions: RequestOptions) {
super(backend, defaultOptions);
}
request(url: string, options?: RequestOptionsArgs): Observable<Response> {
return super.request(url, options).catch((error: Response) => {
if (error.status === 0) {
this._router.navigateByUrl('/no-internet', { skipLocationChange: true });
let timer = 1000; // in milliseconds
Observable.interval(timer * 2).subscribe(x => {
if (timer == 3600000) {
timer = 1000;
} else {
timer = timer * 2;
}
this.onlineCheck(url).then(() => {
// Has internet connection, carry on
window.location.reload();
})
});
}
})
.do((res: Response) => {
// apply logic here for all HTTP request success
});
}
onlineCheck(url) {
let xhr = new XMLHttpRequest();
return new Promise((resolve, reject) => {
xhr.onload = () => {
// Set online status
this.isOnline = true;
resolve(true);
};
xhr.onerror = () => {
// Set online status
this.isOnline = false;
reject(false);
};
xhr.open('GET', url, true);
xhr.send();
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment