热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

如何在Angular6HttpClient中获取响应头

本文介绍如何使用Angular6的HttpClient模块来获取HTTP响应头,包括代码示例和常见问题的解决方案。

在 Angular 6 中,HttpClient 提供了强大的功能来处理 HTTP 请求。为了获取完整的响应信息(包括响应头),我们需要对请求进行一些调整。

下面是一个改进后的 api.service.ts 示例,展示了如何正确地获取响应头:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import { HttpClient } from '@angular/common/http';

import { Injectable, isDevMode } from '@angular/core';

import { NzNotificationService } from 'ng-zorro-antd';

import { UtilService } from '@/services/util.service';

@Injectable()
export class ApiService {
  async request(method, url, data = {}) {
    const headers = {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${localStorage.getItem('token')}`,
    };
    const trim = s => s === undefined || s === null ? '' : s;
    const args = [
      window['baseUrl'],
      url.replace(/:([^&;/?]+)/g, (...s) => trim(data[s[1]])),
    ].join('/');

    const params = Object.keys(data).reduce((obj, key) => {
      obj[key] = trim(data[key]);
      return obj;
    }, {});

    const optiOns= {
      observe: 'response' as 'response', // 获取完整响应对象
      responseType: 'json'
    };

    try {
      const requestData = {
        url: args,
        method: method,
      };
      console.log(args);

      const respOnse= await this.http[method](args, { ...options, headers, params }).toPromise();
      console.log(response.headers); // 打印响应头
      return response.body;
    } catch (e) {
      console.error(e);
      if (e.status !== 401) {
        // this.notify.create('error', `${e.status}`, e.error.message);
      } else {
        localStorage.clear();
        this.util.navigate(['/user/login']);
      }
      throw e;
    }
  }

  delete = (url) => (data?) => this.request('delete', url, data);
  get = (url) => (data?) => this.request('get', url, data);
  patch = (url) => (data?) => this.request('patch', url, data);
  post = (url) => (data?) => this.request('post', url, data);
  put = (url) => (data?) => this.request('put', url, data);

  constructor(
    private http: HttpClient,
    private notify: NzNotificationService,
    private util: UtilService,
  ) { }
}

在上面的代码中,我们通过设置 observe: 'response' 来确保我们可以访问完整的响应对象,包括响应头。然后可以通过 response.headers 来获取响应头的内容。

如果你希望在组件中使用 subscribe 而不是 toPromise,可以按照以下方式进行调整:

1
2
3
4
5
6
7
8
9
10
11
12
async getData(index?) {
  this.loading = true;
  this.currentPage = index;
  this.api.get('accounts')({
    page: this.currentPage,
    'per-page': this.limits
  }).subscribe(resp => {
    console.log(resp.headers); // 打印响应头
    console.log(resp.body); // 打印响应体
    this.loading = false;
    this.data = resp.body;
    this.totalCount = resp.body._meta.totalCount;
  });
}

通过这种方式,你可以轻松地在组件中订阅 HTTP 请求,并同时获取响应头和响应体。


推荐阅读
author-avatar
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有