我正在使用rss2json消费 RSS feed。没有用于启用分页的 page
参数。我可以将一个 count
参数传递给请求。我能够加载提要并获取结果。我使用 ionic 创建了一项服务发出获取提要的请求:
getRssFeed(rssUrl: string, count: number) {
return new Promise<any>(resolve => {
this.http.get(`${ environment.podcast.baseUrl }?rss_url=${ rssUrl }&api_key=${ environment.podcast.apiKey }&count=${ count }`)
.subscribe(data => {
resolve(data);
}, error => {
console.error('Something really bad happened trying to get rss feed.');
console.error(error);
});
});
}
这很好用。我可以取回数据 - 一切都很好。我正在使用 infinite scroll处理分页的组件。再说一次,一切都很好。我从 10 集播客开始。当我想加载更多剧集时,我会注销:
当我滚动时,服务会进行正确的调用,但由于 rss2json 服务没有 page
参数,因此当我更新计数
。
所以我需要做这样的事情:
episodes: Array<any>;
count = 10;
...
this.episodes.splice(this.episodes.length, this.count, data.items);
我需要知道我已经有多少集了。当我第一次到达列表底部时,我将有 10 个(我想每次加载增加 +10)。所以我需要:
- 了解我目前有多少集(10、20、30 等)
- 请求获取更多剧集
- 服务返回 20 集 - 但它总是从零开始。
- 对前 10、20、?? 进行切片返回的剧集,将剩余的 10 集添加到列表末尾。
我不确定如何实现这一目标,可以使用一些指导。
以下是我请求更多剧集的方式:
this.myPodcastService.getRssFeed(this.rssUrl, this.count)
.then(data => {
if (data) {
// console.log('data', data.items);
// data is an object
// data.items is an array of episodes
// this.episodes.splice(this.episodes.length, this.count, data.items);
} else {
...
}
...
});
例如,当我第一次读完剧集时,页面上会显示 10 集。我想出去,再看10集。因此,我需要将 count
变量增加到 20
并将其作为 count
参数传递。
该服务将返回 20 件商品。我想删除前 10 个(它们已经在屏幕上)。我只需要最后 10 集...
现在我会有 20 集。下次滚动时,我需要将 count
增加到 30
。该服务将返回包含 30 个项目的数组。我需要删除(拼接)前 20 个;只留下最后 10 个 - 然后将其添加到 episodes
数组中。
日志记录应显示如下内容:
this.episodes[10]
this.episodes[20]
this.episodes[30]
我希望这是有道理的。我知道我想要实现什么,但我正在努力如何真正做到这一点。感谢您的任何建议!
编辑/解决方案
非常感谢您的建议!如果其他人遇到这个问题,这就是我想出的方法,它正是我所需要的。
// load more episodes using infinite scroll.
loadMoreEpisodes(event) {
console.log('--> loading more episodes');
this.count = (this.count + this.count); // 10, 20, 30...
this.myPodcastService.getRssFeed(this.rssUrl, this.count)
.then(data => {
if (data) {
// append the new episodes to the existing array
this.episodes.push(...data.items.splice(-this.episodes.length, this.count));
event.target.complete();
console.log('this.episodes', this.episodes);
} else {
this.alertCtrl.create({
header: 'Error',
subHeader: 'Something bad happened',
message: 'Something internet related happened & we couldn\'t load the playlist.',
buttons: [{ text: 'Ok', role: 'cancel' }]
}).then(alert => {
alert.present();
});
}
});
}
最佳答案
鉴于 API 不提供获取特定数据的方法,客户端必须请求重复数据,您可以从数组末尾 .splice()
this.episodes.push(...data.splice(-10, 10))
关于javascript - 拼接数组以添加到现有数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54610898/