Skip to content

Instantly share code, notes, and snippets.

@argentinaluiz
Created April 15, 2019 14:47
Show Gist options
  • Save argentinaluiz/cadc4eb5e0b35a8b546b3f3f8a941056 to your computer and use it in GitHub Desktop.
Save argentinaluiz/cadc4eb5e0b35a8b546b3f3f8a941056 to your computer and use it in GitHub Desktop.
Token Interceptor with Storage Service Ionic
import { Injectable } from '@angular/core';
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
import {Observable} from 'rxjs';
import {Storage} from '@ionic/storage';
import { fromPromise } from 'rxjs/observable/fromPromise';
import {flatMap} from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class TokenInterceptorService implements HttpInterceptor {
constructor(private storage: Storage) {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return fromPromise(this.storage.get('token'))
.pipe(
flatMap((token) => {
const newRequest = req.clone({
setHeaders: {
Authorization: 'Bearer ' + token
}
});
return next.handle(newRequest);
})
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment