简体   繁体   English

Angular 4从API响应中获取标头

[英]Angular 4 get headers from API response

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 我想从响应中获取标题,在这种情况下是资源

any idea? 任何的想法?

Clear angular 5 answer 清晰的角度5回答

By default, this.http.whatever's returned observable will be on the data returned, not the HttpResponse. 默认情况下,this.http.whatever返回的observable将返回返回的数据 ,而不是HttpResponse。

If you have a peak at: https://angular.io/api/common/http/HttpClient You'll notice the options take an "observe" parameter of a HttpObserve type. 如果你有一个峰值: https ://angular.io/api/common/http/HttpClient你会注意到这些选项采用了HttpObserve类型的“观察”参数。 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 ) 虽然没有记录HttpObserve是什么,如果你把它作为“响应”,那么你将收到一个HttpResponse<T>的实例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安全性,除非API提供Access-Control-Expose-Headers:否则您将无法看到标Access-Control-Expose-Headers:如果您的api和angular应用程序没有相同的域,则使用自定义标头。

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

When you do .map(this.extractData) the let body = res.json() from this.extractData function takes out everything from the response except the body . 当你执行.map(this.extractData) ,来自this.extractData函数的let body = res.json()从除了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 演示

A bit more of an exotic example in Angular 5 shown below. 下面将介绍Angular 5中的一个奇特的例子。 Using HttpClient to post to a GraphQL server, read the response and then extract a response header value and a response body value. 使用HttpClient发布到GraphQL服务器,读取响应,然后提取响应头值和响应正文值。 The header is Total-Count in this case. 在这种情况下,标题是Total-Count cars is a field (array of Car) under another field data in the body. 汽车是一个领域(汽车阵列)在身体的另一个领域数据 Also shows use of the rxjs first operator. 还显示了使用rxjs 第一个运算符。

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

The return type of the angular Http.get method returns a Response type. 角度Http.get方法的返回类型返回Response类型。 This object has a headers object that contains information about the headers. 此对象有一个标头对象,其中包含有关标头的信息。 It also has a url property. 它还有一个网址属性。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM