Created
July 31, 2017 19:05
-
-
Save AlexVKO/f2d3b800e2ae46b9a924178432c7f0e5 to your computer and use it in GitHub Desktop.
interceptor
This file contains 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 { Injectable } from '@angular/core'; | |
import { Observable } from 'rxjs/Observable'; | |
import 'rxjs/add/operator/map'; | |
import 'rxjs/add/operator/catch'; | |
import 'rxjs/add/operator/do'; | |
import 'rxjs/add/operator/finally'; | |
import Rx from 'rxjs/Rx'; | |
import { Http, | |
XHRBackend, | |
Request, | |
RequestOptions, | |
RequestOptionsArgs, | |
Response } from '@angular/http'; | |
import { ToastController, | |
LoadingController, | |
App } from 'ionic-angular'; | |
import { LoginPage } from '../../pages/login/login'; | |
/* | |
Generated class for the HttpServiceProvider provider. | |
See https://angular.io/docs/ts/latest/guide/dependency-injection.html | |
for more info on providers and Angular DI. | |
*/ | |
@Injectable() | |
export class HttpService extends Http { | |
public pendingRequests: number = 0; | |
public showLoading: boolean = false; | |
public tutorialDone: boolean = !!localStorage.getItem('TUTORIAL_DONE'); | |
public loader: any; | |
constructor(backend: XHRBackend, | |
public toastCtrl: ToastController, | |
public loadingController: LoadingController, | |
protected app: App, | |
public defaultOptions: RequestOptions) { | |
super(backend, defaultOptions); | |
// this.navCtrl = new NavController(); | |
} | |
request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> { | |
return this.intercept(super.request(url, options)); | |
} | |
intercept(observable: Observable<Response>): Observable<Response> { | |
if (this.loader == null) { | |
this.loader = this.loadingController.create({spinner: 'crescent', content: "Please wait...",}); | |
this.loader.present(); | |
} | |
let app = this.app; | |
this.pendingRequests++; | |
return observable | |
.catch((err, source) => { | |
if (err.status === 422) { this._displayToast('Check your form') } | |
if (err.status === 401) { | |
var activeView = app.getRootNav(); | |
if (this.tutorialDone) { | |
activeView.setRoot(LoginPage) | |
} | |
} | |
return Rx.Observable.of(); | |
}) | |
.do((res: Response) => { }, (err: any) => { }) | |
.finally(() => { | |
this.pendingRequests--; | |
if (this.pendingRequests == 0) { | |
this.loader.dismiss(); | |
this.loader = null; | |
} | |
}); | |
} | |
_displayToast(message) { | |
this.toastCtrl.create({ | |
message: message, | |
duration: 2000, | |
position: 'bottom' | |
}).present(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment