Ronald Araújo
Ronald Araújo

Reputation: 1479

Error getting token on interceptor - Type 'Promise<void | Observable<HttpEvent<any>>>' is not assignable to type 'Observable<HttpEvent<any>>'

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.

Upvotes: 1

Views: 250

Answers (2)

georgeawg
georgeawg

Reputation: 48968

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);
}

Upvotes: 0

C.Champagne
C.Champagne

Reputation: 5489

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

Upvotes: 0

Related Questions