1
votes

I am creating an interceptor to send the token along with the requests for the Api.

I use @ionic/storage to store my user information. However, when I try to get the token in the constructor to save to a variable (eg private token: string), my interceptor can not get that value even though the token exists. I believe this happens because the intercept is executed before the this.storage.get function ends.

How can I fix this?

I've tried putting the this.storage.get function inside the intercept, but the return error:

Type 'Promise < void | Observable < HttpEvent < any >>>' is not assignable to type 'Observable< HttpEvent< any>>'. Property '_isScalar' is missing in type 'Promise< void | Observable< HttpEvent>>'.

Look at the code:

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {  
    return this.storage.get('token')
        .then((token) => {
            if (token) {
                const newRequest = req.clone({ setHeaders: { 'Authorization': `Bearer ${token}` } });

                return next.handle(newRequest);
            } else {
                return next.handle(req);
            }
        })
        .catch(() => {
            //TODO: Trata erro
        })
}

Thanks for the help.

2
what does this.storage.get return? (An Http Promise?)Aleksey Solovey
According to the documentation (ionicframework.com/docs/storage), return only Promise.Ronald Araújo

2 Answers

0
votes

Convert the storage promise to an Observable before returning it:

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    var promise = this.storage.get('token')
        .then((token) => {
            if (token) {
                const newRequest = req.clone({ setHeaders: { 'Authorization': `Bearer ${token}` } });

                return next.handle(newRequest);
            } else {
                return next.handle(req);
            }
        })
        .catch((error) => {
            //TODO: Trata erro
            throw error;
        })
    return Observable.fromPromise(promise);
}
0
votes

You can convert your Promise into an Observable with the Observable.fromPromise method.