Within my Angular 2 application, I am faced with the task of authenticating every request by including a token in the header. A service has been set up to handle the creation of request headers and insertion of the token. The dilemma arises from the fact that the function responsible for fetching the token operates asynchronously. As a result, the HTTP get request is triggered before the token can be properly inserted into the header.
Is there a more effective approach to ensure that the HTTP get request waits until the token retrieval process is complete?
Sample 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 function involves an asynchronous JavaScript method call
this.config.getToken(function (responseData) {
if (!responseData.error) {
responseData.headers.append('Authorization', "Bearer " + responseData.token);
return responseData.headers;
});
}