Error when obtaining token in Interceptor - Type 'Promise<void | Observable<Httpevent<any>>' is not Assignable to type 'Observable<Httpevent<any>>'

Asked

Viewed 30 times

1

I’m 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 store in a variable (e.g., private token: string), my Interceptor cannot get that value even if the token exists. I believe this happens because the Intercept runs before the this.storage.get function finishes.

How can I fix this?

I’ve tried to set the function this.storage.get inside the Intercept, but the return error:

"Type 'Promise>>' is not Assignable to type 'Observable>'. Property '_isScalar' is Missing in type 'Promise>>'."

Look at the code:

inserir a descrição da imagem aqui

I appreciate the help.

1 answer

0

The answer came from a stackoverflow.com user.

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

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.