Javascript Angular 4 从 API 响应中获取标头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44292270/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:25:48  来源:igfitidea点击:

Angular 4 get headers from API response

javascriptangulartypescript

提问by Lrawls

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

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

@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);
 }
}

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

我想从该响应中获取标题,在这种情况下是resourceurl

any idea?

任何的想法?

采纳答案by ruedamanuel

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

标头是Response 类的一部分,因此您应该能够在像这样的处理程序中看到它们

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

回答by csga5000

Clear angular 5 answer

清晰的角度 5 答案

By default, this.http.whatever's returned observable will be on the datareturned, not the HttpResponse.

默认情况下,this.http.whatever 返回的 observable 将基于返回的数据,而不是 HttpResponse。

If you have a peak at: https://angular.io/api/common/http/HttpClientYou'll notice the options take an "observe" parameter of a HttpObserve type. While it's not documented what the HttpObserve is, if you put it as "response" then you will instead receive an instance of HttpResponse<T>(https://angular.io/api/common/http/HttpResponse)

如果您在以下位置有一个峰值:https://angular.io/api/common/http/HttpClient您会注意到这些选项采用 HttpObserve 类型的“观察”参数。虽然它没有记录 HttpObserve 是什么,但如果你把它作为“响应”,那么你将收到一个HttpResponse<T>( https://angular.io/api/common/http/HttpResponse)的实例

So, here's an example request:

所以,这是一个示例请求:

this.http.get(url, {observe: 'response'})
    .subscribe(resp => console.log(resp.headers))

Note:Due to browser cors security, you will not be-able to see headers unless the API provides Access-Control-Expose-Headers:with your custom headers if your api and angular app do not have the same domain.

注意:由于浏览器 cors 安全性,Access-Control-Expose-Headers:如果您的 api 和 angular 应用程序没有相同的域,您将无法看到标题,除非 API 提供您的自定义标题。

回答by Nehal

When you do .map(this.extractData)the let body = res.json()from this.extractDatafunction takes out everything from the response except the body.

当你这样做.map(this.extractData)let body = res.json(),从this.extractData功能,从除了响应拿出一切body

Instead if you do following, .map((res: Response) => res), that will return the whole response and you can access all the attributes and assign them to variables.

相反,如果您执行以下操作,.map((res: Response) => res)则将返回整个响应,您可以访问所有属性并将它们分配给变量。

Here's a Plunker demo.

这是一个 Plunker演示

回答by leoncc

A bit more of an exotic example in Angular 5 shown below. Using HttpClient to post to a GraphQL server, read the response and then extract a response header value and a response body value. The header is Total-Countin this case. carsis a field (array of Car) under another field datain the body. Also shows use of the rxjs firstoperator.

下面显示了 Angular 5 中的一个奇特示例。使用 HttpClient 发布到 GraphQL 服务器,读取响应,然后提取响应标头值和响应正文值。在这种情况下,标题是Total-Count汽车是身体中另一个字段数据下的字段(Car数组)。还展示了 rxjs first运算符的使用。

import { HttpClient, HttpHeaders, HttpResponse } from '@angular/common/http';
import { first } from 'rxjs/operators/first'; 
import { Car, CarPage } from '../models/car';  
..........
..........

public find(filter: string, sort: string, limit: number): Observable<CarPage> {
  let headers = new HttpHeaders().set("Content-Type", "application/graphql");
  let carPage: CarPage = { cars: [], totalCount: 0 };
  return this.http.post<HttpResponse<any>>('/graphql',
    `query cars { cars(filter: "${filter}", sort: "${sort}", limit: ${limit}) {
          id
          make
          model
          year 
        }
      }`,
      { headers: headers, observe: "response" }
  )
  .first((_, index) => index === 0, (response: HttpResponse<any>) => {
    let totalCountHeaderValues = response.headers.getAll("Total-Count");
    carPage.totalCount = (totalCountHeaderValues.length > 0) ? parseInt(totalCountHeaderValues[0]) : 0;  
    carPage.cars = response.body.data.cars; 
    return carPage; 
  })
}

回答by jLee

The return type of the angular Http.get method returns a Response type. This object has a headers object that contains information about the headers. It also has a url property.

angular Http.get 方法的返回类型返回一个 Response 类型。该对象有一个 headers 对象,其中包含有关标题的信息。它还有一个 url 属性。

this.http.get(url).map(resp => console.log(resp));