angular - 从 Angular HttpInterceptor 调用 Promise
问题描述
我有一个角度HttpInterceptor
,我需要调用一个定义如下的加密方法:
private async encrypt(obj: any): Promise<string> {
我不确定如何在 HttpInterceptor 中处理这个问题:
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const modified = req.clone({
body: this.encrypt(req.body)
});
return next.handle(modified).pipe(
我不确定如何将这两者联系在一起,以便我可以encrypt
从intercept
函数中正确调用该方法。
解决方案
用于将promisefrom
转换为 observable 并使用switchMap
操作符进行您需要的修改并返回处理程序。
intercept(request: HttpRequest<any>, next: HttpHandler) : Observable<HttpEvent<any>>{
return from( this.encrypt(req.body))
.pipe(
switchMap(data=> { // do the changes here
const modified = req.clone({
body: data
});
return next.handle(modified)
})
);
}
推荐阅读
- css - 在LESS的同一个选择器中使用mixin?
- neural-network - 减少神经网络特征图的空间维度
- nodes - 无法在Ubuntu上安装MemSQL 6.8.5,节点已经存在但无法删除
- laravel - Laravel 没有服务但显示目录和文件夹
- android - 完成所有灰点后禁用“开始推广到生产”按钮
- javascript - 可以在没有 node.js 的情况下使用 Twilio 可编程视频吗?
- jquery - 如何在创建帖子 24 小时后从帖子中删除课程?
- ruby-on-rails - 如何将产品的分类单元从一种产品复制到另一种产品
- javafx - 您可以在运行时覆盖 JavaFX 字体回退吗?
- javascript - 如何计算旋转椭圆上的点