Http Interceptor with Capacitor Storage.get

I’ve tried many times with many ways, but I still can’t get token from Capacitor Storage, to send this into request’s Authorization header. Can you help me?

This code don’t manipulate request.

import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs';
import {
    Storage
} from '@capacitor/core';

@Injectable()
export class JwtInterceptor implements HttpInterceptor {
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        Storage.get({ key: 'token' }).then(token => {
            console.log(token);
            request = request.clone({
                setHeaders: {
                    Authorization: `Bearer ${token}`
                }
            });
        });

        return next.handle(request);
    }
}

but this code returns instead of a string with token, an [object Promise]:

import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs';
import {
    Storage
} from '@capacitor/core';

@Injectable()
export class JwtInterceptor implements HttpInterceptor {
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        request = request.clone({
                setHeaders: {
                    Authorization: `Bearer ${Storage.get({ key: 'token' }).then(token => { return token;
                    })}`
                }});

        return next.handle(request);
    }
}

Nevermind, I found a solution.

Could you post the solution, please?

1 Like

Could you please share the solution? I have the same problem and I still can not find how to solve it.

For anyone who still needs it, I created a post specifically for this issue. I came across this thread when I was searching for a solution so thought to post it here when I found it.:slight_smile:

https://forum.ionicframework.com/t/ionic-4-storage-token-access-for-http-interceptor/158822