Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular HttpClient append headers to HttpHeaders [duplicate]

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

That method returns a httpHeader but it's empty.

enter image description here

like image 678
efarley Avatar asked Dec 14 '17 03:12

efarley


People also ask

How do you use HttpHeaders?

HTTP headers let the client and the server pass additional information with an HTTP request or response. An HTTP header consists of its case-insensitive name followed by a colon ( : ), then by its value. Whitespace before the value is ignored.

What is observe in HttpClient?

Observe Response HttpClient object allows accessing complete response, including headers. In the browser, response body is a JSON object, which can be copied to a typescript interface or class type. Response headers are key/value pairs. Consider the following code that accesses complete response object.


1 Answers

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

and boom! enter image description here

like image 198
efarley Avatar answered Oct 17 '22 10:10

efarley