Can I use promise within HttpInterceptor
? For example:
export class AuthInterceptor implements HttpInterceptor{
this.someService.someFunction()
.then((data)=>{
//do something with data and then
return next.handle(req);
});
}
why I need this? because I need to get a token to add to request header before making the request to the server.
My interceptor:
@Injectable()
export class AuthInterceptor implements HttpInterceptor{
constructor(private authService: AuthService){}
intercept(req: HttpRequest<any>, next: HttpHandler) : Observable<HttpEvent<any>>{
console.log('Intercepted!');
// return next.handle(req);
this.authService.getToken()
.then((token)=>{
console.log(token);
const reqClone = req.clone({
headers: req.headers
.set('Authorization', 'Bearer ' + token)
.append('Content-Type', 'application/json')
});
console.log(reqClone);
return next.handle(reqClone);
})
.catch((err)=>{
console.log('error in interceptor' + err);
return null;
});
}
}
Request:
this.http.post(this.baseURL + 'hero', data)
.subscribe(
(res: any) => {
console.log('Saved Successfully.');
console.log(res);
},
(err: any) => {
console.log('Save Error.' + err);
}
);
Problems I am facing:
->I get this error before the promise is resolved.
You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.
Promise resloves and I get my token but after the error.