Interceptor Angular 4.3 - 在克隆请求上设置多个标头 [英] Interceptor Angular 4.3 - Set multiple headers on the cloned request

查看:16
本文介绍了Interceptor Angular 4.3 - 在克隆请求上设置多个标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚注意到 Header Object可以在以前的 HTTP RequestsOption 中使用,新的拦截器不再支持.

I just noticed that the Header Object that was possible to use in the previous HTTP RequestsOption is not anymore supported in the new Interceptor.

这是新拦截器逻辑:

// Get the auth header from the service.
const authHeader = this.auth.getAuthorizationHeader();
// Clone the request to add the new header.
const authReq = req.clone({headers: req.headers.set('Authorization', authHeader)});

现在,我有两种方法可以在此请求中添加我的标头:

I have, now, two ways to add my headers in this request:

例子:

headers?: HttpHeaders;

    headers: req.headers.set('token1', 'asd')

<小时>

setHeaders?: {
   [name: string]: string | string[];
};

    setHeaders: {
             'token1': 'asd',
             'token2': 'lol'
    }

如何根据此请求有条件地添加多个标头?与我以前对 Header 对象所做的相同:

How can I add multiple headers conditionally on this request? Same to what I used to do with the Header Object:

 myLovellyHeaders(headers: Headers) {
    headers.set('token1', 'asd');
    headers.set('token2', 'lol');
     if (localStorage.getItem('token1')) {
     headers.set('token3', 'gosh');
     }
    }
    const headers = new Headers();
    this.myLovellyHeaders(headers);

推荐答案

Angular 4.3+

在 Interceptor 中设置多标头:

Set multi headers in Interceptor:

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

import {environment} from '../../../../environments/environment';

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

    const headers = new HttpHeaders({
      'Authorization': 'token 123',
      'WEB-API-key': environment.webApiKey,
      'Content-Type': 'application/json'
    });


    const cloneReq = req.clone({headers});

    return next.handle(cloneReq);
  }
}

这篇关于Interceptor Angular 4.3 - 在克隆请求上设置多个标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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