Skip to content

Instantly share code, notes, and snippets.

@drewrygh
Created May 30, 2016 01:33
Show Gist options
  • Save drewrygh/e9133b2b909021e708a157f8169a17a2 to your computer and use it in GitHub Desktop.
Save drewrygh/e9133b2b909021e708a157f8169a17a2 to your computer and use it in GitHub Desktop.
A HTTP module for Ionic apps that handles 'no network connection' errors in a friendly way.
import {Injectable} from 'angular2/core';
import {Http, Request, Response, RequestOptionsArgs} from 'angular2/http';
import {Alert, NavController} from 'ionic-angular';
import {Network, Connection} from 'ionic-native';
@Injectable()
export class NetworkService {
public networkAlert: any;
constructor(private nav: NavController) {
}
public noConnection() {
return (Network.connection === 'none');
}
public showNetworkAlert() {
let networkAlert = Alert.create({
title: 'No Internet Connection',
message: 'Please check your internet connection.',
buttons: [
{
text: 'Cancel',
handler: () => {}
},
{
text: 'Open Settings',
handler: () => {
networkAlert.dismiss().then(() => {
this.showSettings();
})
}
}
]
});
this.nav.present(networkAlert);
}
private showSettings() {
cordova.plugins.diagnostic.switchToWifiSettings();
}
}
@Injectable()
export class SafeHttp {
constructor(private http: Http, private networkService: NetworkService) {
}
public request(url: string | Request, options?: RequestOptionsArgs) {
if (this.networkService.noConnection()) {
this.networkService.showNetworkAlert();
} else { return this.http.request(url, options) }
}
public get(url: string, options?: RequestOptionsArgs) {
if (this.networkService.noConnection()) {
this.networkService.showNetworkAlert();
} else { return this.http.get(url, options) }
}
public post(url: string, body: string, options?: RequestOptionsArgs) {
if (this.networkService.noConnection()) {
this.networkService.showNetworkAlert();
} else { return this.http.post(url, body, options) }
}
public put(url: string, body: string, options?: RequestOptionsArgs) {
if (this.networkService.noConnection()) {
this.networkService.showNetworkAlert();
} else { return this.http.put(url, body, options) }
}
public delete(url: string, options?: RequestOptionsArgs) {
if (this.networkService.noConnection()) {
this.networkService.showNetworkAlert();
} else { return this.http.delete(url, options) }
}
public patch(url: string, body: string, options?: RequestOptionsArgs) {
if (this.networkService.noConnection()) {
this.networkService.showNetworkAlert();
} else { return this.http.patch(url, body, options) }
}
public head(url: string, options?: RequestOptionsArgs) {
if (this.networkService.noConnection()) {
this.networkService.showNetworkAlert();
} else { return this.http.head(url, options) }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment