本文介绍了如何将参数传递给HttpInterceptor?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Angular 4.3.1和HttpClient.有一个HttpInterceptor设置一些标题.

I am using Angular 4.3.1 and HttpClient. There is an HttpInterceptor to set some headers.

在某些http get请求中,我需要设置一个不同的标头.无论如何,我可以为该特定HttpRequest传递一些参数到此HttpInterceptor吗?

In some http get requests I need to set a different header. Is there anyway I can pass some param to this HttpInterceptor for that particular HttpRequest?

@Injectable()
export class MyHttpInterceptor implements HttpInterceptor {

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if(request.custom.param1) // how can i do this
      request = request.clone({
        setHeaders: {
          'header1': 'xxxxxx'
          }
      });

    else
      request = request.clone({
        setHeaders: {
          'header2': 'yyyyyy'
          }
      });


    return next.handle(request);
  }
}

推荐答案

我编写了一个用于处理Http错误响应的拦截器.我想允许特定的Http调用来指示拦截器忽略某些响应状态代码,同时还保留将参数传递给Http调用的功能.这是我最终得到的解决方案. (感谢Aleksey回答您的初衷).

I wrote an interceptor for handling Http error responses. I wanted to allow specific Http calls to instruct the interceptor to ignore certain response status codes, while also retaining the ability to pass params to the Http call. Here is the solution I ended up with. (Thanks, Aleksey for the initial idea in your answer).

扩展HttpParams:

Extend HttpParams:

import { HttpParams } from '@angular/common/http';
import { HttpParamsOptions } from '@angular/common/http/src/params';

// Cause the HttpErrorInterceptor to ignore certain error response status codes like this:
//
//  this.http.get<TypeHere>(`URL_HERE`, {
//    params: new InterceptorHttpParams({ statusCodesToIgnore: [400, 401] }, {
//      complete: 'false',
//      offset: '0',
//      limit: '50'
//    })
//  })

export class InterceptorHttpParams extends HttpParams {
  constructor(
    public interceptorConfig: { statusCodesToIgnore: number[] },
    params?: { [param: string]: string | string[] }
  ) {
    super({ fromObject: params } as HttpParamsOptions);
  }
}

拦截器:

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  return next.handle(req).pipe(
    tap(
      () => {},
      (error: any) => {
        if (error instanceof HttpErrorResponse) {
          const regEx = /^[4-5][0-9][0-9]$/; // 4XX and 5XX status codes

          if (regEx.test(error.status.toString())) {
              const errorMessage = this.getErrorMessageFromStatus(error.status);

              if (!this._shouldIgnoreError(req, error)) {
                console.log(`ERROR INTERCEPTOR: ${error.status}`);
                this.toastService.alert(errorMessage);
              }
          }
        }
      })
  );
}

// Based on `request.params.interceptorConfig.statusCodesToIgnore`, we can see if we should ignore this error.
_shouldIgnoreError(request: HttpRequest<any>, errorResponse: HttpErrorResponse) {
  if (request.params instanceof InterceptorHttpParams
    && Array.isArray(request.params.interceptorConfig.statusCodesToIgnore)
    && request.params.interceptorConfig.statusCodesToIgnore.includes(errorResponse.status)) {

    return true;
  }

  return false;
}

这篇关于如何将参数传递给HttpInterceptor?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 18:57