javascript - 拼接数组以添加到现有数组
问题描述
我正在使用rss2json来使用 rss 提要。没有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);
});
});
}
这很好用。我可以取回数据——一切都很好。我正在使用无限滚动组件来处理分页。再次,一切都很好。我从 10 集播客开始。当我想加载更多剧集时,我正在注销:
当我滚动时,服务会进行正确的调用,但由于rss2json
服务没有page
参数,当我更新count
.
所以我需要做这样的事情:
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
的 to 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 - 从节点 AWS 开发工具包(简单电子邮件服务)发送电子邮件时出现 SignatureDoesNotMatch 错误
- c# - 如何通过代码启用 EnableSqlCommandTextInstrumentation?
- unity3d - 使用 UVC / 外部摄像头 (Unity) 实现 Android AR
- php - PHP 函数即使执行成功也会返回 false
- swift - 如何在 Swift 中将 SDWebImageSwiftUI 保存到照片中?
- react-native - React Native 后台位置 (@mauron85/react-native-background-geolocation) - 安装问题,如何将模块与 Expo 托管工作流链接?
- algorithm - 最大子数组问题如何具有最优子结构?
- apache-kafka - Kafka 流状态存储分布
- javascript - 在Vue3中传递对象数组并循环遍历它的正确语法是什么
- typescript - D3.js:“this”隐含类型“any”,因为它没有类型注释