Created
April 15, 2019 14:47
-
-
Save argentinaluiz/cadc4eb5e0b35a8b546b3f3f8a941056 to your computer and use it in GitHub Desktop.
Token Interceptor with Storage Service Ionic
This file contains hidden or 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 {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