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

查看:101
本文介绍了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天全站免登陆