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.
this.storage.get
return? (An Http Promise?) – Aleksey Solovey