How to pass a param to HttpInterceptor?

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

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

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;
}
链接地址: http://www.djcxy.com/p/40454.html

上一篇: SendBird用文件作为封面创建GroupChannel

下一篇: 如何将一个参数传递给HttpInterceptor?