繁体   English   中英

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

[英]Read response headers in component file Angular

我需要读取组件文件中的响应头,请求类型是发布请求。 需要访问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);
    });

  }

皮克特

链接可能重复

从链接中提取

您是否使用 access-control-expose-headers 从服务器端公开 X-Pagination? 因为不是所有的头都允许从客户端访问,你需要从服务器端公开它们

同样在您的前端,您可以使用新的 HTTP 模块来使用 {observe: 'response'} 获得完整的响应,例如

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

请参阅文档

更新 3:

问题出在您的服务器端代码上。

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

应该是这个

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

您在服务器端错误地设置了标头,而在客户端读取了错误的标头。

更新您的服务器端代码,然后使用我之前推荐的上述现有客户端代码。

  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