Created
February 12, 2017 14:12
-
-
Save carmichaelize/c8f203df12b608b6e44d98959fe9815c to your computer and use it in GitHub Desktop.
Testing for an internet connection.
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 } 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