我从wordpress中收集数据,并在按钮单击后使用几个请求将它们推送到数组中,该按钮运行initGetComments()函数。
数组:
singleCommentResults: CommentsItem[] = [];
commentsResults = [];Init函数:
initGetComments(){
var btn = document.getElementById("comment_btn");
if (!btn.classList.contains('clicked')){
var posts = document.getElementsByClassName('single-post');
for( var i = 0; i < posts.length; i++ ) {
this.getComments(posts[i].id).subscribe(data => {
this.singleCommentResults = data;
this.commentsResults.push(this.singleCommentResults[0]);
console.warn("commentsResults =", this.commentsResults);
})
}
} else {
console.log('Comments already downloaded!')
}
btn.classList.add("clicked");
}获取函数:
getComments(ID:string): Observable<CommentsItem[]> {
console.log(ID);
return this.http
.get(`https://public-api.wordpress.com/rest/v1/sites/en.blog.wordpress.com/posts/${ID}/replies/?number=1`)
.map(res =>
res.comments.map(
item =>
new CommentsItem(
item.post.ID,
item.ID,
item.author.name,
item.author.avatar_URL,
item.date,
item.raw_content
)
)
);
}此时此刻,所有这些请求都是在“同时”发送的,我想在前面的请求完成后发送其中的每一个请求。
发布于 2019-03-22 10:45:35
使用递归函数实现它,如下所示:
Init功能:更改
initGetComments(){
var btn = document.getElementById("comment_btn");
if (!btn.classList.contains('clicked')){
var posts = document.getElementsByClassName('single-post');
// Call to new function to fetch comments for first post
this.getSyncComment(0, posts)
} else {
console.log('Comments already downloaded!')
}
btn.classList.add("clicked");
}同步获取注释的新函数
getSyncComment(n, posts){
if (n == posts.length) {
return
}
this.getComments(posts[n].id).subscribe(data => {
const singleCommentResults = data; // Changed
this.commentsResults.push(singleCommentResults[0]); // Changed
console.warn("commentsResults =", this.commentsResults);
// Make recursive call to fetch comment for next post
this.getSyncComment(n+1, posts);
});
} https://stackoverflow.com/questions/55207592
复制相似问题