Getting Local Storage Value inside Http Client Interceptor

I am using the angular 4.3 interceptor method. https://medium.com/@danielcrisp/async-http-interceptors-with-angular-4-3-9e6e795da562.

Here is how everything takes place. The user logs in, the password and username are passed to the auth service where I then can get a token. I then set that token to ionic’s local storage. I pass that value to getting the value in a function inside the auth service. I then call that get token function inside my interceptor. I then convert that storage promise to an observable and wrap it around what my interceptor returns.

There’s a couple things I’ve done to sort of mitigate the issue.

  1. The issue is not stemmed from my interceptor - because I have removed the local storage functionality out entirely and replaced with a random number generator promise, which worked fine.
  2. If I place this.storage.get(‘token’, 1) inside my interceptor constructor, I’m still getting the same result of ‘null’.
  3. If I place the get token storage promise outside of the interceptor I’m able to retrieve that token.

My guess is that it has something to do with the combination of the two - interceptor and local storage.

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return this.auth.getTokens().switchMap(tokenv => {
            console.log(tokenv,'this is tokenv')
            const authReq = req.clone({
                setHeaders: {
                Authorization: tokenv.toString()
                }
                });

                return next.handle(authReq)
           })
}

-- auth.ts

getTokens() :Observable<any>{
  return Observable.fromPromise(this.storage.get('token'));
}

The newest supported version of Angular for Ionic is 4.1.3:

Everything newer is not supported and will break in surprising ways.

One thing I would look at is being extra conservative about ensuring storage is ready. How about making getTokens() use this.storage.ready().then(() => this.storage.get('token'))?

Unfortunately, this did not work. Thanks for the advice though!

I think you might be right. I’m just going to try the optimal way for 4.1.3