I'm attempting to assign a token value to all request headers using the new angular 5 HTTP client. Take a look at my code snippet:
import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';
import {Observable} from "rxjs/Observable";
import { Storage } from '@ionic/storage';
import {Globals} from '../globals/globals';
@Injectable()
export class Interceptor implements HttpInterceptor {
token: string;
constructor(private storage: Storage, private global: Globals){
this.storage.get('token').then((val) => {
this.token = val;
});
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log(this.token) //undefined "only for first time on app start"
req = req.clone({
setHeaders: {
'Token': this.token,
'Version': this.global.version,
}
});
return next.handle(req);
}
}
Although adding the token to the request header works, there is a minor issue. It does not work initially. This occurs due to the asynchronous nature of JavaScript, where req.clone gets executed before retrieving the token from storage. As Ionic storage returns a promise, how can one handle this situation for the initial run?