在Angular HttpClient拦截器中使用promise
发布时间:2020-12-17 07:57:45 所属栏目:安全 来源:网络整理
导读:我可以在HttpInterceptor中使用promise吗?例如: export class AuthInterceptor implements HttpInterceptor{this.someService.someFunction() .then((data)={ //do something with data and then return next.handle(req); });} 为什么我需要这个?因为我
|
我可以在HttpInterceptor中使用promise吗?例如:
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. 承诺resloves我得到我的令牌但错误后.
是的,您可以将所需的服务注入到拦截器的构造函数方法中,并在拦截的实现中检索该值,创建一个新的更新的http请求并处理它.
我会在一段时间内用一个例子更新我的答案,我目前正在进行中 更新: 我对承诺不满意,所以你可以尝试以下方法: import { fromPromise } from 'rxjs/observable/fromPromise';
@Injectable()
export class AuthInterceptor implements HttpInterceptor{
constructor(private authService: AuthService){}
intercept(req: HttpRequest<any>,next: HttpHandler) : Observable<HttpEvent<any>>{
return fromPromise(this.authService.getToken())
.switchMap(token => {
const headers = req.headers
.set('Authorization',application/json');
const reqClone = req.clone({
headers
});
return next.handle(reqClone);
});
}
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- 在Angular2中的Reactives FormModule中禁用FormGroup控件
- 捕获脚本变量中的bash时间输出
- bash脚本错误[:!=:一元运算符
- twitter-bootstrap – Bootstrap响应图表和图表
- 别责怪框架:我使用 AngularJS 和 ReactJS 的经验
- 如何使用navParams获取整个对象 – Ionic 3 Angular 4
- 如何在Angular中使用带有SASS的Bootstrap 4
- Webservice_17_客户端创建Handler,服务端接受Handler
- ng-repeat中的AngularJS Bootstrap UI btn-checkbox
- shell – ksh自动完成和以前的命令在一起
