Error getting token on interceptor - Type 'Promisevoid | ObservableHttpEventany 'is not assignable to type' ObservableHttpEventany '

1

I'm creating an interceptor to send the token along with the requests to Api.

I use @ionic/storage to save 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 runs before the this.storage.get function ends.

How can I fix this?

I have tried to put the this.storage.get function inside the intercept, but the return error:

"Type 'Promise > >' is not assignable to type 'Observable>'. Property '_isScalar' is missing in type 'Promise >'. "

See the code:

Thanks for the help.

    
asked by anonymous 07.06.2018 / 16:12

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

}

    
09.06.2018 / 04:41