Search code examples
angularcorsangular2-http

Not getting some header values in Angular 4


I am querying back-end like following with angular 4

    this.classzService.query({
      page: this.page,
      size: this.itemsPerPage,
      sort: this.sort(),
      url: url
    }).subscribe(
      (res: Response) => this.onQuerySuccess(res.json(), res.headers),
      (res: Response) => this.onError(res.json())
      );

    private onQuerySuccess(data, headers: Headers) {
       this.links = this.parseLinks.parse(headers.get('Link'));
       this.totalItems = headers.get('X-Total-Count');        
    }

Issue is headers.get('Link') and headers.get('X-Total-Count') gives me Null values.

When I check my chrome browser I see those values are there. What can be the issue. enter image description here


Solution

  • This generally occurs in case of CORS when the origins are different. When you enable CORS at your server, by default it only exposes some default headers. In your case as you have two custom headers Link and X-Total-Count. So at your server you need to explicitly expose these headers using Access-Control-Expose-Headers. If you are using ASP.NET WebApi then you can do by adding this to your WebApiConfig class:

    config.EnableCors(new EnableCorsAttribute("*", "*", "GET, POST, OPTIONS, PUT, DELETE", "Link, X-Total-Count"));
    

    You can check this concept here and here.