In my angular 2 application I need to authenticate each request by inserting a token in the header. I have a service that creates the request headers and insert the token. The problem is, the method that retrieves the token is asynchronous. So in the code below, the http get is executed before the token can be inserted into the header.
Is there a better way to force the http get to wait until the token is trieved?
code:
getData(query: Vehicle): Observable<ResultWrapper> {
this.spinnerService.show();
return this.http
.get(`${this.myService.apiEndpoint}/vehicles?name=${query.make}`,
{ headers: this.myService.getHeaders() })
.map(this.extractData)
.catch(this.exceptionService.catchBadResponse)
.finally(() => {
this.spinnerService.hide();
});
}
myService:
getHeaders(): any {
// this is call to an asynchronous javascript method
this.config.getToken(function (responseData) {
if (!responseData.error) {
responseData.headers.append('Authorization', "Bearer " + responseData.token);
return responseData.headers;
});
}