[英]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.