0

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;
        });
}
noobie
  • 2,427
  • 5
  • 41
  • 66
  • how abt HTTP Interceptors ? Intercept your req before it goes , add headers & then go. That way your token related code would be in single place. – Parth Ghiya Apr 12 '17 at 04:50
  • I was mentioned in this post http://stackoverflow.com/questions/34464108/angular2-set-headers-for-every-request that interceptors were not supported in Angular 2. He also has an example of extending the http class, however, the authentication call is still synchrounous. – noobie Apr 12 '17 at 04:55

1 Answers1

0

You certainly can work out a fix - but maybe there's a better way to implement this. For example, your Auth service (myService) will keep a cached token and pass it to the requester (e.g. getAccessToken() method that would return localStorage.getItem('auth_token')). Then you would use something like

let headers = new Headers({ 'Authorization': 'Bearer ' + this.myService.getAccessToken() });

Then you'll just need to trap errors on getData call (code 401) for when the token expires and just request a new one.

Alic W
  • 128
  • 7