angular - 如何将参数传递给 HttpInterceptor?

标签 angular typescript interceptor

我正在使用 Angular 4.3.1 和 HttpClient。有一个 HttpInterceptor 来设置一些 header 。

在某些 http get 请求中,我需要设置不同的 header 。无论如何,我可以为特定的 HttpRequest 将一些参数传递给此 HttpInterceptor 吗?

@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 在您的回答中提出了最初的想法)。

扩展 HttpParams:

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

// 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: (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;
}

关于angular - 如何将参数传递给 HttpInterceptor?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46075602/

相关文章:

node.js - 获取带有 ID 的方法

jquery - 将类中所有元素的函数绑定(bind)到事件的 Angular 方式

java - spring 拦截器不向@RestController 服务添加 header

spring - @Autowired 在 CXF 拦截器 + Spring 应用程序中不起作用

javascript - Nativescript定时器模块与JS setInterval的区别

angular - 从 Angular2 应用程序将文件上传到 Lumen API

reactjs - TypeScript 与 Redux 容器斗争

javascript - Google map /TypeScript - 无法一致识别 google.maps.Place

javascript - typescript 错误 : Duplicate identifier 'LibraryManagedAttributes'

spring - 拦截器未通过Spring Boot初始化和调用