如何使用异步服务到角度httpClient拦截器 [英] How use async service into angular httpClient interceptor

查看:131
本文介绍了如何使用异步服务到角度httpClient拦截器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Angular 4.3.1和HttpClient,我需要通过异步服务将请求和响应修改为httpClient的HttpInterceptor,

Using Angular 4.3.1 and HttpClient, I need to modify the request and response by async service into the HttpInterceptor of httpClient,

修改请求的示例:

export class UseAsyncServiceInterceptor implements HttpInterceptor {

  constructor( private asyncService: AsyncService) { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // input request of applyLogic, output is async elaboration on request
    this.asyncService.applyLogic(req).subscribe((modifiedReq) => {
        const newReq = req.clone(modifiedReq);
        return next.handle(newReq);
    });
    /* HERE, I have to return the Observable with next.handle but obviously 
    ** I have a problem because I have to return 
    ** newReq and here is not available. */
  }
}

响应的问题不同,但是我需要再次应用applyLogic来更新响应. 在这种情况下,角度向导建议如下:

Different problem for the response, but I need again to applyLogic in order to update the response. In this case, the angular guide suggests something like this:

return next.handle(req).do(event => {
    if (event instanceof HttpResponse) {
        // your async elaboration
    }
}

但是"do()运算符-它在不影响流值的情况下向Observable添加了副作用".

But the "do() operator—it adds a side effect to an Observable without affecting the values of the stream".

解决方案: 关于请求的解决方案由bsorrentino显示(已接受的答案),有关响应的解决方案如下:

return next.handle(newReq).mergeMap((value: any) => {
  return new Observable((observer) => {
    if (value instanceof HttpResponse) {
      // do async logic
      this.asyncService.applyLogic(req).subscribe((modifiedRes) => {
        const newRes = req.clone(modifiedRes);
        observer.next(newRes);
      });
    }
  });
 });

因此,如何通过异步服务将请求和响应修改到httpClient拦截器中?

Therefore, how modify request and response with async service into the httpClient interceptor?

解决方案: 利用rxjs

推荐答案

我认为反应流存在问题.方法 intercept 期望返回一个 Observable ,并且您必须用 Observable 返回的 Observable 异步结果. strong> next.handle

I think that there is a issue about the reactive flow. The method intercept expects to return an Observable and you have to flatten your async result with the Observable returned by next.handle

尝试一下

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
      return this.asyncService.applyLogic(req).mergeMap((modifiedReq)=> {
        const newReq = req.clone(modifiedReq);
        return next.handle(newReq);
    });
}

您也可以使用 switchMap 代替 mergeMap

这篇关于如何使用异步服务到角度httpClient拦截器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆