Angular HttpClient 将标头附加到 HttpHeaders [英] Angular HttpClient append headers to HttpHeaders

查看:37
本文介绍了Angular HttpClient 将标头附加到 HttpHeaders的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从 HttpServer 升级到 HttpClientService,作为其中的一部分,我必须将我的标头从 Headers 切换到 HttpHeaders.但是由于某种原因,我的自定义标题不再被附加.我需要更新什么才能附加标题?

I am upgrading from the HttpServer to the HttpClientService and as part of that I have to switch my headers from Headers to HttpHeaders. However For some reason my custom headers are no longer being appended. What do I need to update to have the headers appended?

  private getHeaders(headers?: HttpHeaders): HttpHeaders {
    if (!headers) {
      headers = new HttpHeaders();
    }
    headers.delete('authorization');
    const token: any = this.storageService.getItem('token');
    if (token) {
      headers.append('Authorization', 'Bearer ' + token);
    }
    const user: User = this.storageService.getObject('user');
    if (user && Object.keys(user).length) {
      headers.append('X-Session-ID', user.uuid);
      headers.append('X-Correlation-ID', this.uuidService.generateUuid());
    }
    return headers;
  }

该方法返回一个 httpHeader 但它是空的.

That method returns a httpHeader but it's empty.

推荐答案

HttpHeaders.append 返回附加了值的标题的克隆,它不会更新对象.您需要将返回值设置为标题.

HttpHeaders.append returns a clone of the headers with the value appened, it does not update the object. You need to set the returned value to the headers.

angular/packages/common/http/src/headers.ts

append(name: string, value: string|string[]): HttpHeaders { 
  return this.clone({name, value, op: 'a'}); 
} 

所以要附加标题,您可以这样做.

So to append the headers you do this.

let headers: HttpHeaders = new HttpHeaders();
headers = headers.append('Content-Type', 'application/json');
headers = headers.append('x-corralation-id', '12345');

和繁荣!

这篇关于Angular HttpClient 将标头附加到 HttpHeaders的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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