我试图每次都从API返回所有结果。相反,我的结果各不相同。 for循环跳过请求并返回随机返回的记录数。有人可以帮忙吗?
我尝试使用异步和等待功能。我也曾尝试实现promise.all,但不认为我为api请求正确设置了它。
// Get all ref codes and group by into an array.
async getAllRefCodes() {
const url = `${this.irRefCodes}`;
const refCodes = [];
let totalPage = 0;
const params1 = new HttpParams().set('size', '20').set('page', `0`);
await this.http.get(`${url}`, {params: params1 }).toPromise().then((data) => {
console.log(data['page'].totalPages);
console.log(data['page'].totalElements);
totalPage = data['page'].totalPages;
});
for (let x = 0; x < totalPage; x++) {
this.getRefCodesByPage(refCodes, url, x);
console.log('Done');
}
await Promise.all(refCodes);
console.log(refCodes);
}
// Getting all ref codes from API per page.
async getRefCodesByPage(refCodes, url, pageNumber) {
const params = new HttpParams().set('size', '20').set('page', `${pageNumber}`);
const promise = new Promise ((resolve, reject) => {
this.http.get(`${url}`, {params: params})
.toPromise().then((refCodeData) => {
const refCode = refCodeData['_embedded'].refCodes;
refCodes.push(...refCode);
});
resolve();
return promise;
});
await Promise.all(promise);
}
希望每次都能获得所有记录。常量
答案 0 :(得分:0)
移动for循环以在subscribe块内逐页获取引用代码(这是我认为的代码中的主要问题)
getAllRefCodes() {
const url = `${this.irRefCodes}`;
const refCodes = [];
let totalPage = 0;
const params1 = new HttpParams().set('size', '20').set('page', `0`);
this.http.get(`${url}`, {params: params1 }).subscribe((data) => {
console.log(data['page'].totalPages);
console.log(data['page'].totalElements);
totalPage = data['page'].totalPages;
for (let x = 0; x < totalPage; x++) {
this.getRefCodesByPage(refCodes, url, x);
console.log('Done');
}
});
console.log(refCodes);}
getRefCodesByPage(refCodes,url,pageNumber){
const params = new HttpParams()。set('size','20')。set('page',${pageNumber}
);
this.http.get(${url}
,{params:params})。subscribe((refCodeData)=> {
const refCode = refCodeData ['_ embedded']。refCodes;
refCodes.push(... refCode);
})