gpt4 book ai didi

javascript - 拉动刷新数据重复

转载 作者:行者123 更新时间:2023-11-29 14:47:37 24 4
gpt4 key购买 nike

我正在创建一个从 joomla K2 网站提取文章的 Ionic 应用程序。我正在使用 $http 并以 '?format=json' 结束我的 url,并且工作正常。但是,我从中提取数据的网站每隔几分钟就会更新其文章,因此我需要一种方法让用户能够刷新页面。我已经实现了 Ionics pull to refresh,它运行良好,除了它不是仅仅拉入新文章,而是将所有文章附加到我的数组中。无论如何,是否可以迭代当前文章的时间戳或 ID(我在 localStorage 中缓存文章)以引入新文章?我的工厂看起来像这样:

.factory('Articles', function ($http) {
var articles = [];
storageKey = "articles";

function _getCache() {
var cache = localStorage.getItem(storageKey );
if (cache)
articles = angular.fromJson(cache);
}


return {
all: function () {
return $http.get("http://jsonp.afeld.me/?url=http://mexamplesite.com/index.php?format=json").then(function (response) {
articles = response.data.items;
console.log(response.data.items);
return articles;
});
},

getNew: function () {
return $http.get("http://jsonp.afeld.me/?url=http://mexamplesite.com/index.php?format=json").then(function (response) {
articles = response.data.items;
return articles;
});
},

get: function (articleId) {
if (!articles.length)
_getCache();
for (var i = 0; i < articles.length; i++) {
if (parseInt(articles[i].id) === parseInt(articleId)) {
return articles[i];
}
}
return null;
}
}
});

和我的 Controller :

.controller('GautengCtrl', function ($scope, $stateParams, $timeout, Articles) {
$scope.articles = [];
Articles.all().then(function(data){
$scope.articles = data;
window.localStorage.setItem("articles", JSON.stringify(data));
},

function(err) {
if(window.localStorage.getItem("articles") !== undefined) {
$scope.articles = JSON.parse(window.localStorage.getItem("articles"));
}
}

);

$scope.doRefresh = function() {
Articles.getNew().then(function(articles){
$scope.articles = articles.concat($scope.articles);
$scope.$broadcast('scroll.refreshComplete');
});
};
})

最佳答案

使用 underscore.js 来简化过滤功能。

例如:

获取已加载项目的所有 id(我相信有一些独特的字段,如 id)

http://underscorejs.org/#pluck

var loadedIds = _.pluck($scope.articles, 'id');

如果 item.id 已经在 loadedIds 列表中,则拒绝所有项目。

http://underscorejs.org/#reject

http://underscorejs.org/#contains

var newItems = _.reject(articles, function(item){ 
return _.contains(loadedIds, item.id);
});

加入新项目和现有项目:

$scope.articles = newItems.concat($scope.articles);

http://underscorejs.org/#union

$scope.articles = _.union(newItems, $scope.articles);

实际上 _.union() 可以管理和删除重复项,但我会使用 item.id 进行手动过滤。

关于javascript - 拉动刷新数据重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30798064/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com