如何在Angular 5 HttpInterceptor中添加多个标头 [英] How to add multiple headers in Angular 5 HttpInterceptor

查看:274
本文介绍了如何在Angular 5 HttpInterceptor中添加多个标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习如何使用HttpInterceptor向应用程序对API所做的每个HTTP请求添加几个标头.我有这个拦截器:

I'm trying to learn how to use HttpInterceptor to add a couple of headers to each HTTP request the app do to the API. I've got this interceptor:

import { Injectable } from '@angular/core';

import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';

import { Observable } from 'rxjs/Observable';


@Injectable()
export class fwcAPIInterceptor implements HttpInterceptor {
  intercept (req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

  const authReq = req.clone({
    headers: req.headers.set('Content-Type', 'application/json')
  });

  console.log('Intercepted HTTP call', authReq);

  return next.handle(authReq);
}
}

除了'Content-Type'标头之外,我还需要添加一个'Authorization',但我没有做这件事(Angular HttpHeaders的文档只是方法列表,没有任何解释).

Apart of the 'Content-Type' header I need to add an 'Authorization' but I don't how to do it (the documentation of Angular HttpHeaders is just the list of the methods, without any explanation).

我该怎么办?谢谢!

推荐答案

@Injectable()
export class fwcAPIInterceptor implements HttpInterceptor {
  intercept (req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

  const authReq = req.clone({
    headers: new HttpHeaders({
      'Content-Type':  'application/json',
      'Authorization': 'my-auth-token'
    })
  });

  console.log('Intercepted HTTP call', authReq);

  return next.handle(authReq);
}

这篇关于如何在Angular 5 HttpInterceptor中添加多个标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆