如何在角度 6 中更改拦截器中的内容类型?

Ali*_*ade 4 angular-http-interceptors angular6

有些服务需要令牌,有些服务需要不同的内容类型。我应该如何在拦截器文件中管理它们?

Nim*_*ard 5

您可以在拦截器函数上获取或设置所有请求标头。以下代码显示了用于处理此更改的标头属性:

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    if (request.headers.has('Content-Type'))
       contentType = request.headers.get('Content-Type');

    request = request.clone({
      setHeaders: {
        'Authorization': `Bearer ${this.auth.getToken()}`,
        'Content-Type': (contentType != 'application/json' ? 'application/text' :  contentType)
      }
    });
    return next.handle(request);
  }
Run Code Online (Sandbox Code Playgroud)