Angular 在对 Wordpress REST API 使用类型化 GET 请求时,从 X-WP-Total 响应 header 中检索所有帖子的计数

Angular retrieve count of all posts from X-WP-Total response header while using a typed GET request to Wordpress REST API

我正在开发一个与 Wordpress REST API 对话的 Angular 应用程序。我需要从服务器获取所有帖子的计数。那条数据可以通过X-WP-Total响应得到header.

我在网上四处寻找答案,发现了 ,但似乎那里的大多数答案都集中在未类型化的 HttpClient.post()<any> 方法上。正如我所说,我正在努力向服务器发送 GET 请求以获取所有帖子,并且我还需要获取帖子总数。我还想输入我的请求以捕获错误。

到目前为止,我的代码如下所示:

frontpage.component.ts:

import { Component, OnInit } from '@angular/core';
import { Question } from '../question';
import { QuestionService } from '../question.service';

@Component({
  selector: 'app-frontpage',
  templateUrl: './frontpage.component.html',
  styleUrls: ['./frontpage.component.css']
})
export class FrontpageComponent implements OnInit {

  constructor(private questionService: QuestionService) { }

  questions: Question[] = [];

  getQuestions(): void {
    this.questionService.getQuestions()
        .subscribe(questions => {
          this.questions = questions;
          console.log(questions.headers.get('X-WP-Total')); // <-- error
      
        });
  }

  ngOnInit(): void {
    this.getQuestions();
  }

}

question.service.ts:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Question } from './question';

@Injectable({
  providedIn: 'root'
})
export class QuestionService {

  constructor(private http: HttpClient) { }

  /** GET all questions from the server */
  getQuestions(): Observable<Question[]> {
    return this.http.get<Question[]>("http://localhost/wordpress/wp-json/wp/v2/posts", 
      { observe: 'response'}); <-- error
  }
}

question.ts(打字界面):

export interface Question {
    "id": number;
    "date": string;
    "date_gmt": string;
    "guid": {
        "rendered": string
    };
    "modified": string;
    "modified_gmt": string;
    "slug": string;
    "status": string;
    "type": string;
    "link": string;
    "title": { 
        "rendered": string; 
    };
    "content": {
        "rendered": string;
        "protected": boolean;
    };
    "excerpt": {
        "rendered": string;
        "protected": boolean;
    };
    "author": number;
    "featured_media": number;
    "comment_status": string;
    "ping_status": string;
    "sticky": boolean;
    "template": string;
    "format": string;
    "meta": string[];
    "categories": number[];
    "tags": string[];
    "_links": {
        "self": [
            {
                "href": string;
            }
        ];
        "collection": [
            {
                "href": string;
            }
        ];
        "about": [
            {
                "href": string;
            }
        ];
        "author": [
             {
                "embeddable": boolean;
                "href": string;
            }
        ];
        "replies": [
            {
                "embeddable": boolean;
                "href": string;
            }
        ];
            "version-history": [
            {
                "count": number;
                "href": string;
            }
        ];
        "wp:attachment": [
            {
                "href": string;
            }
        ];
        "wp:term": [
            {
                "taxonomy": string;
                "embeddable": boolean;
                "href": string;
            },
            {
                "taxonomy": string;
                "embeddable": boolean;
                "href": string;
            }
        ];
        "curies": [
            {
                "name": string;
                "href": string;
                "templated": boolean;
            }
        ]
    }
}

我的代码运行 error-free,但是如果我修改 QuestionService 的方法并在 URL 参数后添加 { observe: 'response'} object 我得到以下输入错误:

Type 'Observable<HttpResponse<Question[]>>' is not assignable to type 'Observable<Question[]>'.
Type 'HttpResponse<Question[]>' is missing the following properties from type 'Question[]': 
length, pop, push, concat, and 26 more.

除此之外,在组件 class 文件中,如果我尝试通过简单地从 questions.headers.get() 方法中挖掘出来来将 header 记录到控制台,我得到以下输入错误:

Property 'headers' does not exist on type 'Question[]'.

我该如何继续?

编辑:Stackblitz 此处:https://stackblitz.com/edit/angular-ivy-dd5wea?

get()方法的observe选项告诉HttpClient你想要完整的响应,并使return方法类型为HttpResponse.

getQuestions(): Observable<HttpResponse<Question[]>> {
    return this.http.get<Question[]>(
      'https://public-api.wordpress.com/wp/v2/sites/aleksejjj83211792.wordpress.com/posts',
      { observe: 'response' }
    );
}

在您的组件中,您可以调用服务方法并使用 response.headers 属性.

读取 header
getQuestions(): void {
    this.questionService.getQuestions().subscribe((respnse) => {
      const headreValue = respnse.headers.get('X-WP-Total');
      this.questions = [...respnse.body!]
    });
}

Stackblitz 演示:- https://stackblitz.com/edit/angular-ivy-quxx7e?file=src%2Fapp%2Fapp.component.ts

参考资料:- https://angular.io/guide/http#reading-the-full-response