简体   繁体   English

角响应标头值

[英]Angular response headers value

I get a request from WP Rest Api in Angular 我收到来自Angular的WP Rest Api的请求

service.ts 服务

get(): Observable<any>{
return  this.http.get<any>('mysite.com/posts?categories=4&per_page=2'));
}

app-component.ts app-component.ts

  ngOnInit() {
this.RestApi.get()
  .subscribe(
    e => {
      console.log(e);
      console.log('headers: ' + e.headers);
    });}

response 响应

DevTools - Network 1 : https://i.stack.imgur.com/HBI7i.png DevTools-网络 1https : //i.stack.imgur.com/HBI7i.png

DevTools - Console: DevTools-控制台:

(2) [{…}, {…}]
    0: {id: 100, date: "2018-02-27T18:38:59", ...}
    1: {id: 98, date: "2018-02-27T18:38:34", ...}
    length: 2__proto__: Array(0)

headers: undefined

So, why in Network I see Response Headers, but in Console I have undefined? 那么,为什么在网络中可以看到响应标题,而在控制台中却没有定义? How I can get value of 'X-WP-TotalPages'? 如何获得“ X-WP-TotalPages”的价值? What I do wrong? 我做错了什么?

Thx for attention! 谢谢! I hope for your help :) 希望对您有所帮助:)

http.get(...) does not return an object with a headers property at all. http.get(...)完全不返回带有headers属性的对象。

https://angular.io/api/common/http/HttpClient#get https://angular.io/api/common/http/HttpClient#get

If you use the observe option you can get the full response like so: 如果使用observe选项,您将获得完整的响应,如下所示:

this.http.get<Config>('mysite.com/posts?categories=4&per_page=2', { observe: 'response' });

https://angular.io/guide/http#reading-the-full-response https://angular.io/guide/http#reading-the-full-response

You will need to pass { observe: 'response' } option into your http.get method so that it can return an Observable of typed HttpResponse rather than just the JSON data. 您将需要在您的http.get方法中传递{ observe: 'response' } http.get { observe: 'response' }选项,以便它可以返回类型为HttpResponse的Observable而不是返回JSON数据。

To show each of the headers, you can do something like this 要显示每个标题,您可以执行以下操作

this.RestApi.get()
  .subscribe(
    e => {
      console.log(e);
      // debugger; 
      this.headers = e.headers.keys().map(key =>
        console.log(`${key}: ${e.headers.get(key)}`));
    });
}

Also you could set a debugger in the code (uncomment the line) so that the browser will break right at the line, and then you can inspect the values as needed. 另外,您可以在代码中设置调试器(取消注释该行),以便浏览器将在该行处中断,然后可以根据需要检查值。

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

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