Angular 4从API响应获取标头 [英] Angular 4 get headers from API response

查看:153
本文介绍了Angular 4从API响应获取标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在向API发送请求,它返回一个数据数组,但是我不知道如何从该url中提取标头,这就是我在服务中尝试过的方法

I'm sending a request to an API, it returns an array of data, but I don't know how to extract the headers from that url, this is what i've tried in my service

@Injectable()
export class ResourcesService {
private resourcesurl = "http://localhost:9111/v1/resources";

constructor(private http: Http) { }

getResources() {
  let headers = new Headers();
  headers.append("api_key", "123456");
  return this.http.get(this.resourcesurl, { headers: headers 
 }).map(this.extractData).catch(this.handleError);
}
getresourceheaders(){
  let headers = new Headers();
  headers.append("api_key", "123456");
  let options = new RequestOptions();
  let testsss = options.headers
  let headerapi = this.http.request(this.resourcesurl, options);
  let test = this.http.get(this.resourcesurl, { headers: headers });
  console.log(headerapi);
}
private extractData(res: Response) {
  let body = res.json();
  return body.data || {};
}
private handleError(error: Response | any) {
let errMsg: string;
if (error instanceof Response) {
  const body = error.json() || '';
  const err = body.error || JSON.stringify(body);
  errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
  errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
 }
}

我想从该响应中获取标头,在本例中为 resourceurl

I want to get the headers from that response that in this case is resourceurl

有什么主意吗?

推荐答案

标头是

The headers are part of the Response class, so you should be able to see them in a handler like

http.get('/path/to/resource')
  .subscribe((res:Response) => {
    console.log(res.headers);
    // you can assign the value to any variable here
  });

这篇关于Angular 4从API响应获取标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆