简体   繁体   English

Angular - 如何使用 Wordpress 创建分页 REST ZDB974238714CA8DE634A7CE1D083A1

[英]Angular - How to create pagination with Wordpress REST API?

I am working on an Angular app (similar to how Stack Overflow works) that displays posts (or questions if you will) and other related data from Wordpress REST API. I am working on an Angular app (similar to how Stack Overflow works) that displays posts (or questions if you will) and other related data from Wordpress REST API. What I am trying to accomplish is to have a running number in the URL eg http://localhost:4200/frontpage/:pagenumber and have that reflect the content on the site.我想要完成的是在 URL 例如http://localhost:4200/frontpage/:pagenumber中有一个运行号码,并反映网站上的内容。 I have successfully created an app in which users can click on pagination control buttons to navigate between pages (while running the same component the whole time), but the content on the web page does not update with that and that is what I need to fix.我已经成功创建了一个应用程序,用户可以在其中单击分页控制按钮在页面之间导航(同时始终运行相同的组件),但是web 页面上的内容没有随之更新,这就是我需要修复的. So, say the user navigates to http://localhost:4200/frontpage/2 the app should fire a function call that sends a GET request to Wordpress REST API: /wp/v2/posts?page=2&per_page=3 and the resulting data should be reflected with that action. So, say the user navigates to http://localhost:4200/frontpage/2 the app should fire a function call that sends a GET request to Wordpress REST API: /wp/v2/posts?page=2&per_page=3 and the resulting该行动应反映数据。

I am also experiencing an issue where the page count header X-WP-TotalPages returned by the API gives me a page count lower than the actual page count of the site.我还遇到了一个问题,即 API 返回的页数 header X-WP-TotalPages给我的页数低于网站的实际页数 My Wordpress site has 6 public posts but X-WP-TotalPages returns a value of 1 when limiting the result set to 3 posts per_page .我的 Wordpress 站点有 6 个公共帖子,但X-WP-TotalPages在将结果集限制为 3 个帖子per_page时返回值1 What gives?是什么赋予了?

You will find my Stackblitz here: https://stackblitz.com/edit/angular-ivy-wqptx4?file=src/app/frontpage/frontpage.component.ts你会在这里找到我的 Stackblitz: https://stackblitz.com/edit/angular-ivy-wqptx4?file=src/app/frontpage/frontpage.component.ts

Here are the important parts:以下是重要部分:

app-routing.module.ts:应用程序路由.module.ts:

const routes: Routes = [
  { path: 'frontpage/:page', component: FrontpageComponent },
  { path: '', redirectTo: '/frontpage/1', pathMatch: 'full' },
];

question.service.ts:问题.service.ts:

/** GET all questions */
getQuestions(page: number): Observable<Question[]> {
  return this.http.get<Question[]>(
    `https://public-api.wordpress.com/wp/v2/sites/aleksejjj83211792.wordpress.com/posts?page=${page}&per_page=3`
  );
}

/** GET headers from response with the 'observe' option */
getHeaders(): Observable<HttpResponse<Question[]>> {
  return this.http.get<Question[]>(
      'https://public-api.wordpress.com/wp/v2/sites/aleksejjj83211792.wordpress.com/posts', { observe: 'response' }
  );
}

frontpage.component.html: frontpage.component.html:

<!-- A row of pagination control buttons -->
<nav aria-label="Page navigation example">
    <ul class="pagination">
        <li *ngFor="let page of [].constructor(pageCount); let i = index" class="page-item">
            <a routerLink="/frontpage/{{ i + 1 }}" class="page-link" href="#">{{ i + 1 }}</a>
        </li>
    </ul>
</nav>

frontpage.component.ts: frontpage.component.ts:

export class FrontpageComponent implements OnInit {

    constructor(
        private questionService: QuestionService,
        private router: Router,
        private route: ActivatedRoute
      ) {
        router.events
          .pipe(filter((event) => event instanceof NavigationEnd))
          .subscribe((event: NavigationEnd) => {
            const splitURL = event.url.split('/');
            console.log('navigated to ', event.url);
            this.getQuestions(+splitURL[2]);
          });
      }

    getQuestionCount(): void {
        this.questionService.getHeaders().subscribe((questions) => {
        this.pageCount = +questions.headers.get('X-WP-TotalPages');
        console.log('pageCount', this.pageCount);
    });

    ngOnInit(): void {
        this.getQuestionCount();
        const pageParam = +this.route.snapshot.paramMap.get('page');
        this.mergedArray$ = this.getQuestions(pageParam);
    }
}

I realized that if I manually go to the browser's address bar, type in a page number and hit Enter key the content on the site actually does update according to the page number, but pressing the pagination control button at the bottom of the page does nothing, so I need to fix that.我意识到,如果我手动go 到浏览器的地址栏,输入页码并按 Enter 键,网站上的内容实际上会根据页码进行更新,但按下页面底部的分页控制按钮没有任何反应,所以我需要解决这个问题。

There is a minor mistake in getHeaders within QuestionService . QuestionService中的getHeaders有一个小错误。 When you call /posts without a parameter how many items you wish to have per page wordpress will apply a default pageSize - and use that default to calculate the total pages.当您在不带参数的情况下调用/posts时,wordpress 将应用默认的 pageSize - 并使用该默认值来计算总页数。

So easily adding the pageSize to the call does the trick.如此轻松地将 pageSize 添加到调用中就可以了。

Change it like that:像这样改变它:

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

} }

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

相关问题 如何使用 Django Rest Framework API 对 Angular2 进行分页 - How To Pagination Angular2 with Django Rest Framework API Angular Wordpress REST API - 如何创建带有新标签的帖子(结合 Observables)? - Angular Wordpress REST API - How to create a post with new tags (combine Observables)? Angular 7:如何使用 API 数据路由创建简单的分页 - Angular 7 : How to create simple pagination with routing for API data 使用API​​ Rest和angular的自定义wordpress登录 - Custom wordpress login with API Rest and angular 通过Wordpress REST API渲染Angular组件 - Render Angular component via Wordpress REST API 仅在从REST API接收数据后,我应该如何使用分页呈现Angular MatTable? - How should I render a Angular MatTable with pagination only after data is received from a REST API? 如何使用Spring Boot在angular 4中的HTTP Get方法中传递分页对象以使用REST API从REST API中获取数据 - How to pass Pagination object in HTTP Get method in angular 4 for fetching data from REST API using spring boot Angular 为 Wordpress REST API 命名数据中的字符创建接口 - Angular create interface for Wordpress REST API posts data (unrecognized characters in interface property names) 如何从 Angular 创建和更新产品到 REST API - How to create and update products to a REST API from Angular Angular 8:如何从 json REST API 创建枚举 - Angular 8: How to create enum from json REST API
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM