Created
September 8, 2018 11:40
-
-
Save iSanjayAchar/4ddd336b42d40066ee4e4f92acbfaef2 to your computer and use it in GitHub Desktop.
Ionic 2+ | Angular 2+ | @angular/http module | HTTP 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 { NgModule, ErrorHandler } from '@angular/core'; | |
import { BrowserModule } from '@angular/platform-browser'; | |
import { IonicApp, IonicErrorHandler, IonicModule, AlertController, LoadingController } from 'ionic-angular'; | |
import { MyApp } from './app.component'; | |
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; | |
import { HttpModule, RequestOptions, XHRBackend } from '@angular/http'; | |
import { LocalStorageProvider } from '../providers/local-storage/local-storage'; | |
import { httpService } from '../providers/http/http'; | |
@NgModule({ | |
declarations: [ | |
MyApp | |
], | |
imports: [ | |
BrowserModule, | |
IonicModule.forRoot(MyApp), | |
HttpModule | |
], | |
bootstrap: [IonicApp], | |
entryComponents: [ | |
MyApp | |
], | |
providers: [ | |
StatusBar, | |
SplashScreen, | |
{ | |
provide: ErrorHandler, | |
useClass: IonicErrorHandler | |
}, | |
{ | |
provide: httpService, | |
useFactory: httpFactory, | |
deps: [XHRBackend, RequestOptions, LoadingController, AlertController] | |
}, | |
httpService, | |
LocalStorageProvider | |
] | |
}) | |
export class AppModule {} | |
export function httpFactory(backend: XHRBackend, options: RequestOptions, loader: LoadingController, alert: AlertController) { | |
return new httpService(backend, options, loader, alert); | |
} |
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 { LoadingController, AlertController } from 'ionic-angular'; | |
import { Http, XHRBackend, RequestOptions, Request, RequestOptionsArgs, Response, Headers } from '@angular/http'; | |
import { LocalStorageProvider } from '../local-storage/local-storage'; | |
import { Observable } from 'rxjs/Observable'; | |
import 'rxjs/add/operator/map'; | |
import 'rxjs/add/operator/catch'; | |
import 'rxjs/add/operator/finally'; | |
@Injectable() | |
export class httpService extends Http { | |
baseUrl: string = 'http://example.com'; | |
constructor( | |
backend: XHRBackend, | |
options: RequestOptions, | |
private loader: LoadingController, | |
public alertCtrl: AlertController | |
) { | |
super(backend, options); | |
options.headers.append('x-access-token', localStorage.getItem('_token')); | |
} | |
request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> { | |
let loader = this.loader.create({ | |
content: "Please wait..." | |
}); | |
if (typeof url === 'string') { | |
if (!options) { | |
options = { | |
headers: new Headers() | |
}; | |
} | |
options.headers.set('x-access-token', localStorage.getItem('_token')); | |
} else { | |
url.url = this.baseUrl + url.url; | |
url.headers.set('x-access-token', localStorage.getItem('_token')); | |
} | |
loader.present(); | |
return super.request(url, options).catch(this.auth(this)).finally(() => loader.dismiss()); | |
} | |
private auth(self: httpService) { | |
return (resp: Response) => { | |
if (resp.status === 401) { | |
localStorage.clear(); | |
let alert = this.alertCtrl.create({ | |
title: 'Internal Server Error', | |
subTitle: "Whoops, look's like you're logged out. Please sign in to continue", | |
buttons: ['Login'] | |
}); | |
alert.present(); | |
} else if (resp.status >= 500) { | |
let alert = this.alertCtrl.create({ | |
message: "Look's like there is an issue in our servers. Please re-open the app" | |
}) | |
alert.present(); | |
} | |
return Observable.throw(resp); | |
} | |
} | |
} |
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 { Component } from '@angular/core'; | |
import { IonicPage, NavController, NavParams } from 'ionic-angular'; | |
import { httpService } from '../../providers/http/http'; | |
/** | |
* Generated class for the LoginPage page. | |
* | |
* See http://ionicframework.com/docs/components/#navigation for more info | |
* on Ionic pages and navigation. | |
*/ | |
@IonicPage() | |
@Component({ | |
selector: 'page-login', | |
templateUrl: 'login.html', | |
}) | |
export class LoginPage { | |
isLoginIn: boolean = false; | |
user: any = { | |
email: '', | |
password: '' | |
} | |
constructor( | |
private http: httpService, | |
private toast: ToastController | |
) { } | |
login() { | |
this.http.post('/api/v1/login/', this.user) | |
.subscribe(resp => { | |
//Your logic | |
}, err => { | |
//Your logic | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I have similar function in Ionic3, it works. But In ionic4, the loading controller caller becomes async. It can make problems if API finished before loader started render, the loader will can not be closed.
If the page contains two APIs, ex user profile page may contains two API to retrieve two different resources, the logic can be more complex.