lomas09
lomas09

Reputation: 1104

Angular interceptor return value outside observable

I am using Angular 6 and I am coding an API which uses access tokens as an authentication mechanism. Basically I set the Authorization Bearer token on the headers using an interceptor and then send it as a request.

At first I was storing the access token in local storage and getting it from there to set it as the authorization bearer. However, i am now using IndexDB since I will begin working with service workers and PWA. So I am now using an asynchronous library @ngx-pwa/local-storage which wraps everything in observables.

Now I don't know how to return the value outside of the function because I need to get the token in a synchronomous manner before sending the next interception handle. What is the best way of doing this?

this.localStorage.getItem('access_token').subscribe(token => {
  const cloned = req.clone({
    headers: req.headers.set('Authorization', 'Bearer ' + token)
  });
  return next.handle(cloned); // does not work
});

Upvotes: 0

Views: 764

Answers (2)

martin
martin

Reputation: 96899

So this.localStorage.getItem('access_token') gets the key from IndexDB and returns an Observable. The only thing you need to do is wait until the getItem completes and then continue with next.handle(cloned) which means you can use for example the concatMap operator:

return this.localStorage.getItem('access_token')
  .pipe(
    concatMap(token => {
      const cloned = req.clone({
        headers: req.headers.set('Authorization', 'Bearer ' + token)
      });
      return next.handle(cloned);
    })
  );

The above code will go to your interceptor.

Upvotes: 1

Simon K
Simon K

Reputation: 2857

You could try using the async/await keywords:

async someFunction(...){
    ....
    const token = await this.localStorage.getItem('access_token').toPromise();
    const cloned = req.clone({
        headers: req.headers.set('Authorization', 'Bearer ' + this._auth.ACCESS_TOKEN)
    });
    // Do whatever you need to with 'cloned'
}

The await keyword will force execution of the function to wait until the localStorage.getItem call has completed.

Upvotes: 0

Related Questions