Angular6 HttpClient :怎么能获取response header

发布于 2022-09-11 18:36:30 字数 3110 浏览 18 评论 0

api.service.ts

import { HttpClient } from '@angular/common/http';
import { Injectable, isDevMode } from '@angular/core';
import { NzNotificationService } from 'ng-zorro-antd';
// import { Observable } from 'rxjs';
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: any = [[
      // isDevMode() ? '/api' : '//yanduapi.t.oc1.xyz/v2',
      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 response = {
      observe: "response" as 'body', // to display the full response
      responseType: "json"
    }
    if (method === 'get' || method === 'delete') {
      args.push({ headers, params, response });
    } else {
      args.push(params, { headers });
    }

    try {
      // const requestData_old = JSON.parse(localStorage.getItem('requestData'));
      const requestData = {
        url: args[0],
        method: method,
        // timestamp: (new Date()).getTime(),
      }
      console.log(args)

      return await this.http[method](...args).subscribe(resp => {
        // Here, resp is of type HttpResponse<MyJsonData>.
        // You can inspect its headers:
        console.log(resp);
        // And access the body directly, which is typed as MyJsonData as requested.
        // console.log(resp.body.someField);
      });

      // }
    } catch (e) {
      console.log(e)
      const { status, statusText } = e;
      if (status != 401) {
        // this.notify.create('error', `${status}`, e.error.message);
      }
      if (status === 401) {
        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,
  ) { }
}
  async getData(index?) {
    this.loading = true;
    this.currentPage = index;
    const data = await this.api.get('accounts')({
      page: this.currentPage,
      'per-page': this.limits
    })
    console.log(data)
    // this.loading = false;
    // this.data = data;
    // this.totalCount = data._meta.totalCount;
  }

在封装的api中打印的 console.log(resp); 还是只有response body的内容 应该怎么写能拿到response header的内容呢 然后我之前是用toPromise 如果改成subscribe应该怎么调用呢 在component中

请大神指个路 小白刚开始学 之前的封装不是我写的

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

枯叶蝶 2022-09-18 18:36:30
const response = {
  observe: "response" as 'body', // to display the full response
  responseType: "json"
}

改为:

    const response = {
  observe: "response", // to display the full response
  responseType: "json"
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文