首页 > 解决方案 > 拼接数组以添加到现有数组

问题描述

我正在使用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)。所以我需要:

我不确定如何实现这一点并且可以使用一些方向。

以下是我要求更多剧集的方式:

 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();
                });
            }
        });
}

标签: javascriptarraysionic-framework

解决方案


鉴于 API 没有提供获取特定数据的方法,其中客户端必须请求重复数据,您可以.splice()从数组末尾

this.episodes.push(...data.splice(-10, 10))

推荐阅读