Skip to content

Instantly share code, notes, and snippets.

@carmichaelize
Created February 12, 2017 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carmichaelize/c8f203df12b608b6e44d98959fe9815c to your computer and use it in GitHub Desktop.
Save carmichaelize/c8f203df12b608b6e44d98959fe9815c to your computer and use it in GitHub Desktop.
Testing for an internet connection.
import { Component } from '@angular/core';
@Component({
template: `
<h1>Is Online: {{ isOnline }}</h1>
<span (click)="clickHandler()">Click Me</span>
`,
})
export class MyComponent {
private baseUrl = 'http://www.test.com';
private isOnline = false;
onlineCheck() {
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', this.baseUrl, true);
xhr.send();
});
}
clickHandler() {
this.onlineCheck().then(() => {
// Has internet connection, carry on
}).catch(() => {
// Has no internet connection, let the user know
alert('Sorry, no internet.');
});
}
constructor() {
// Run the initial online test
this.onlineCheck();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment