/**
* This will get all posts from a default WordPress REST API
* First we see how many pages there are
* Then we make subsequent XHR requests (via Axios)
* That paginate through every page of posts
*/
// Importing Axios for simple AJAX request
const axios = require('axios')
// Importing RxJS @ v6.0.0-alpha.3
const { Observable, from, range } = require('rxjs')
const { switchMap, concatMap } = require('rxjs/operators')
const endpoint = 'http://demo.wp-api.org/wp-json/wp/v2/posts'
/**
* This sets up the initial request and the Observable stream
* In the return from the endpoint, the Axios request headers will have x-wp-totalpages,
* which gives us... the total pages of posts ;)
*/
const posts$ = Rx.Observable.from(axios.get(endpoint))
/**
* We now know the total number of pages,
* so we'll switch to a new Observable that is just a range of numbers
* We'll start with 1, and end with whatever the total number of pages is
* This gives us a stream of 1--n--n--n... (example: 1, 2, 3, 4...)
*/
.switchMap((
{ headers }, // using ES6 function header destructuring and arrow functions here
) => Rx.Observable.range(1, Number(headers['x-wp-totalpages'])))
/**
* We can now paginate through all posts, getting 10/page
* concatMap will fire off a request, waits until it completes, and then fire the next one
* In each subsequent firing, we ask for the next page of posts
*/
.concatMap(page =>
axios.get(endpoint, {
params: {
page,
},
}),
)
.subscribe(
// data here is an Array of WordPress Posts, tacking .length shows us how many per page we are getting
({ data }) => console.log(data.length),
err => console.log('Oh no, an error!', err),
)
3 回答
解决这个问题的一种方法是使用RxJS
我们将构建一个小的Observable流,它将:
输出所有发布数据
不要强迫我们事先知道帖子或页面的总数
不强制在分页的情况下跟踪"where we're at"
我们将使用的库:
Axios(简化HTTP GET,因为它在节点和浏览器环境中都有效)
RxJS v6(目前是Alpha版本,但此处的API与RxJS 5相同)
您的环境和用例会有所不同,对于此示例,我将进入Node环境 .
资源
RunKit example with the code above(唯一的区别是在RunKit示例中导入RxJS v5,因为v6尚不可用,但此示例的API没有区别)
RxJS In Depth - Ben Lesh(视频,来自主要维护者的RxJS的良好入门级别)
The introduction to Reactive Programming you've been missing(@andrestaltz RxJS简介的最佳文字资源)
https://www.learnrxjs.io/
Destructuring objects as function parameters in ES6
Arrow Functions on MDN(检查基本和高级语法)
您可以使用 wp_remote_retrieve_body($url) 或 wp_remote_post($url) 来获取发布数据而不是其他API使用情况 . wp_remote函数独立于默认分页 .
大型查询可能会损害网站性能,因此per_page的上限为100条记录 . 如果您希望检索超过100条记录,例如构建所有可用类别的客户端列表,您可以发出多个API请求并将结果合并到您的应用程序中 . see this for complet expalin