How to pass a param to HttpInterceptor?

断了今生、忘了曾经 提交于 2019-11-27 17:20:35

问题


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

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);
  }
}

回答1:


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).

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);
  }
}

Interceptor:

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;
}



回答2:


Maybe there's a better way to handle this problem, but as a workaround you can create and pass custom HttpParams to request and then check them in the interceptor. For example:

export class CustomHttpParams extends HttpParams {
  constructor(public param1: boolean) {
   super();
  }
}

Using this class in http call:

this.http.get('https://example.com', {
  params: new CustomHttpParams(true)
})

And now in interceptor:

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  if (request.params instanceof CustomHttpParams && request.params.param1) 
    request = request.clone({
      setHeaders: {
        'header1': 'xxxxxx'
      }
    });
  else
    request = request.clone({
      setHeaders: {
        'header2': 'yyyyyy'
      }
    });

  return next.handle(request);
}


来源:https://stackoverflow.com/questions/46075602/how-to-pass-a-param-to-httpinterceptor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!