简体   繁体   English

读取组件文件 Angular 中的响应头

[英]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需要访问X-Pagination对象,但我想在我的component文件中而不是在服务文件中读取它,这是我尝试的方式

  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?您是否使用 access-control-expose-headers 从服务器端公开 X-Pagination? 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 模块来使用 {observe: 'response'} 获得完整的响应,例如

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

see : Documentation请参阅文档

Update 3:更新 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'));
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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