我可以在里面使用 promiseHttpInterceptor
吗?例如:
export class AuthInterceptor implements HttpInterceptor{
this.someService.someFunction()
.then((data)=>{
//do something with data and then
return next.handle(req);
});
}
为什么我需要这个?因为在向服务器发出请求之前,我需要获取一个令牌以添加到请求标头。
我的拦截器:
@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;
});
}
}
要求:
this.http.post(this.baseURL + 'hero', data)
.subscribe(
(res: any) => {
console.log('Saved Successfully.');
console.log(res);
},
(err: any) => {
console.log('Save Error.' + err);
}
);
我面临的问题:
->我在承诺解决之前收到此错误。
You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.
Promise resloves,我得到了我的令牌,但在错误之后。