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

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

问题描述

我刚刚注意到标题对象有可能在以前的HTTP请求中使用OptionsOption在新的拦截器中不再支持。

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.

这是新的Interceptor 逻辑:

It's the new Interceptor logic:

// 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:

示例:

Example:

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


推荐答案

新的HTTP客户端使用不可变的头对象。您需要存储对前面标题的引用来改变对象:

The new HTTP client works with immutable headers object. You need to store a reference to the previous headers to mutate the object:

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

请参阅为什么HttpParams不能在多角度4.3中运行,以了解为什么需要存储对返回值的引用。

See Why HttpParams doesn't work in multiple line in angular 4.3 to understand why you need to store the reference to the returned value.

这对于标题是一样的:

It's the same thing for headers:

export class HttpHeaders {
  ...
  set(name: string, value: string|string[]): HttpHeaders {
    return this.clone({name, value, op: 's'});
  }

  private clone(update: Update): HttpHeaders {
    const clone = new HttpHeaders();
    clone.lazyInit =
        (!!this.lazyInit && this.lazyInit instanceof HttpHeaders) ? this.lazyInit : this;
    clone.lazyUpdate = (this.lazyUpdate || []).concat([update]);
    return clone;
  }

要了解有关拦截器背后的机制的更多信息,请阅读:

To learn more about mechanics behind interceptors read:

  • Insider’s guide into interceptors and HttpClient mechanics in Angular

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

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