1

Need to get value from header. Need to get X-Count property value using angular. My code has some errors

Backend code

@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<OrderDTO>> getAllOrders(){
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.add("X-Count",String.valueOf(orderService.ordersCount()));
    httpHeaders.setAccessControlAllowHeaders(Arrays.asList("X-Count"));
    httpHeaders.setAccessControlExposeHeaders(Arrays.asList("X-Count"));
    return new ResponseEntity<List<OrderDTO>>(orderService.getAllOrders(),httpHeaders,HttpStatus.OK);
}

Service directory

getOrderCount(): Observable<any> { return this.httpClient.get<any>(this.BASE_URL); }

Component directory

this.placeOrderService.getOrderCount().subscribe(count => {
  console.log(count.headers.get('X-Count'));
}, error1 => {
  console.log(error1);
});

2 Answers 2

1

The response body doesn't return all the data you may need. Sometimes servers return special headers or status codes to indicate certain conditions that are important to the application workflow.

Tell HttpClient that you want the full response with the observe option

getOrderCount(): Observable<any> {
  return this.httpClient.get<any>(this.BASE_URL, { observe: 'response' });
}

Now HttpClient.get() returns an Observable of typed HttpResponse rather than just the JSON data.

(Source: docs)

Sign up to request clarification or add additional context in comments.

1 Comment

If this answer helped you, kindly accept it as the right answer :) See here: stackoverflow.com/help/someone-answers
0

You need also to observe the response like this:

getOrderCount() : Observable<HttpResponse<any>>{
    return this.http.get<HttpResponse<any>>(this.BASE_URL, {observe: 'response'}).pipe(
         tap(response=> console.log('headers', response.headers))
    );
}

1 Comment

never use pipe method. normally use subscribe method in Observable class

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.