angular6 封装http请求 toPromise 为什么在success拦截器中没有响应头的信息 应该怎么能拿到呢

api.service.ts

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: 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;
    }, {});
    if (method === 'get' || method === 'delete') {
      args.push({ headers, params });
    } 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()
      }

      return await this.http[method](...args)
        .toPromise().then(this.handleSuccess)


      // }
    } 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;
    }
  }

  handleSuccess(res: Response) {
    console.log(res)
    // let body: {} = res['_body'];
    // console.log(body)
    // if (body) {
    //   return {
    //     data: body || {},
    //     statusText: res.statusText,
    //     status: res.status,
    //     success: true
    //   };
    // }
    // else {
    //   return {
    //     statusText: res.statusText,
    //     status: res.status,
    //     success: true
    //   };
    // }
  }

  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')({
      // search_all: this.search.value.searchAll,
      page: this.currentPage,
      'per-page': this.limits
    }).then(res=>{
      console.log(res)
    })
    console.log(data)
    // this.loading = false;
    // this.data = data;
    // this.totalCount = data._meta.totalCount;
  }

clipboard.png

handleSuccess中打印的res只有body 怎么能拿到响应头的信息呢 求大神指路
刚学的小白

阅读 5k
2 个回答

如果handleSuccess方法输出的对象只有body,说明res不是Response类型,httpclient的get方法有多个重载,有些返回Response对象,有些返回简单的json对象,取决于参数。你调用的是返回简单json的版本。

下面这段代码

if (method === 'get' || method === 'delete') {
  args.push({ headers, params });
} else {
  args.push(params, { headers });
}

改为:

if (method === 'get' || method === 'delete') {
  args.push({ headers, params,observe: 'response' });
} else {
  args.push(params, { headers });
}

你就可以取到response对象。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进