简体   繁体   中英

Read response headers in component file Angular

I need to read the response headers in component file, type of request is post request. need to access the X-Pagination object, but I want to read that in my component file not in service file here is how I tried

  ngOnInit(): void {
    this.paginator.pageSize = 25;
    this.endUserReportService.getDailyReport().subscribe(response => {
      console.log('Response of end-user-report: ', response);
      this.reports = response;
      this.dataSource = new MatTableDataSource(this.reports);
      this.dataSource.paginator = this.paginator;
      this.dataSource.sort = this.sort;


      // here is how I'm trying, but its not working

      this.http.get<any>(this.endUserReportService.URL, { observe: 'response' })
        .subscribe(resp => {
          console.log(resp.headers.get('X-Pagination'));
        });


    }, error => {
      console.log('Error occured while end-user fetching report: ', error);
    });

  }

皮克特

Possible Duplicate of Link

Extracted from link

Have you exposed the X-Pagination from server side using access-control-expose-headers? because not all headers are allowed to be accessed from the client side, you need to expose them from the server side

Also in your frontend, you can use new HTTP module to get a full response using {observe: 'response'} like

http
  .post<any>(this.endUserReportService.URL, {observe: 'response'})
  .subscribe(resp => {
    console.log(resp.headers.get('X-Pagination'));
  });

see : Documentation

Update 3:

The issue is on your server side code.

res.header('pagination', 'informationAboutPagination');
    let pagination = 'blablabla'
    res.header('Access-Control-Expose-Headers', pagination);

it should be this

let pagination = 'blablabla'
res.header('X-Pagination', pagination);

you had your headers set incorrectly on server side, and you where reading the wrong header on client side.

update your server side code and then use the existing client side code like above which i recommended before.

  this.http.get<any>(this.endUserReportService.URL, {
      headers: new HttpHeaders().set('X-Pagination', {}),
      observe: 'response'
  }).map(res => {
      console.log(res.headers.get('X-Pagination'));
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM