Skip to content

Instantly share code, notes, and snippets.

@ldmarz
Last active April 17, 2021 12:00
Show Gist options
  • Save ldmarz/6b1c1b08e91fbf0f540058e753545481 to your computer and use it in GitHub Desktop.
Save ldmarz/6b1c1b08e91fbf0f540058e753545481 to your computer and use it in GitHub Desktop.
Http interceptor for ionic 3, this allow us to make actions like obtain a JWT token before send the request. Sample of implementation at http://ldmarz.com/ionic3-http-interceptor/
import {Http, RequestOptionsArgs, Response, RequestOptions, ConnectionBackend, Headers} from '@angular/http';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';
import { Storage } from '@ionic/storage';
export class HttpProvider extends Http {
constructor (connectionBackend: ConnectionBackend, requestOptions: RequestOptions, public storage: Storage ) {
super(connectionBackend, requestOptions);
}
get(url: string, options?: RequestOptionsArgs): Observable<Response> {
return Observable.fromPromise (
this.getRequestOptionArgs()
).mergeMap((options) => { return super.get(url, options) });
}
post(url: string, body: string, options?: RequestOptionsArgs): Observable<Response> {
return Observable.fromPromise (
this.getRequestOptionArgs()
).mergeMap((options) => { return super.post(url, body, options) })
}
put(url: string, body: string, options?: RequestOptionsArgs): Observable<Response> {
return Observable.fromPromise (
this.getRequestOptionArgs()
).mergeMap((options) => { return super.put(url, body, options) })
}
getRequestOptionArgs(options?: RequestOptionsArgs) {
return this.storage.get('token')
.then((token) => {
if (options == null) {
options = new RequestOptions();
}
if (options.headers == null) {
options.headers = new Headers();
}
if (token !== null) {
options.headers.append('Authorization','Bearer ' + token);
}
options.headers.append('Content-Type', 'application/json');
return options;
})
}
}
@behrooz66
Copy link

Hi there, Thanks for this very useful code. Can you help me add a piece to it to support refresh tokens?
I have been trying for two days and I have been stuck.
Look here please: https://stackoverflow.com/questions/45655939/ionic-storage-get-returns-null-only-on-the-second-call-within-method

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment