import { logout } from './../actions/auth' ; import { Store } from '@ngrx/store' ; import { Injectable , Injector } from '@angular/core' ; import { Http , Headers , RequestOptionsArgs , Request , Response , ConnectionBackend , RequestOptions , } from '@angular/http' ; import { ToastController } from 'ionic-angular' ; import { Observable } from 'rxjs/Observable' ; import 'rxjs/add/operator/do' ; import 'rxjs/add/observable/throw' ; import { AppState } from './../reducers' ; import { AuthProvider } from './../providers' ; @ Injectable ( ) export class HttpWrapper extends Http { public store : Store < AppState > ; public toastCtrl : ToastController ; constructor ( protected _backend , protected _defaultOptions , public authProvider , public injector ) { super ( _backend , _defaultOptions ) ; this . toastCtrl = this . injector . get ( ToastController ) ; } request ( url , options = new RequestOptions ( { } ) ) { this . onRequest ( url , options ) ; return super . request ( url , options ) . do ( ( r ) => { this . onResponse ( url , r ) ; } , err => { this . onError ( url , err ) ; } ) ; } private onRequest ( url , options = new RequestOptions ( { } ) ) { console . log ( 'url' , url ) ; } private onResponse ( url , response ) { } private onError ( url , err ) { if ( err . status >= 400 && err . status < 600 ) { if ( err . status === 403 ) { let toast = this . toastCtrl . create ( { message : 'Unauthorized. Loging out in 3 secs...' , duration : 3000 , } ) ; toast . onDidDismiss ( ( data , role ) => this . authProvider . logout ( ) ) ; toast . present ( ) ; } else { const body = JSON . parse ( err . _body ) ; this . toastCtrl . create ( { message : body [ 0 ] . message , duration : 3000 , } ) . present ( ) ; } } return Observable . throw ( err ) ; } }