gpt4 book ai didi

javascript - 在 Angular 中存储和使用定期更新的数据的最佳方式

转载 作者:行者123 更新时间:2023-11-28 07:40:01 24 4
gpt4 key购买 nike

我是 Angular 新手,我正在尝试创建一个应用程序,该应用程序每 5 分钟从动态生成的 JSON 文件中提取数据,并使用新数据更新 View 。 JSON 文件包含网站的所有数据,即 slider 和事件列表的数据。我读到全局数据可以存储在 $rootScope 中,或者使用 .service 或 .factory 检索和提供服务。我尝试了不同的方法但没有成功,我迷失了。定期从整个应用程序的 api 提取数据、存储和使用数据的最佳方法是什么?

目前我有这个代码:

app.factory("Poller", function Poller($http, $timeout){
var data = {'slider' : [], 'activities' : []};
var getData = function(){
$http.get('http://example.com/json.php')
.then(function(r){
data = r.data;
});
$timeout(getData, 1000*60*5);
}
getData();

return{
data: data
}
});

app.controller('ListController', function(Poller){
this.activities = Poller.data.activities;
});

最佳答案

我认为您正在寻找这样的东西:

参见plnkr

app.factory("Poller", function Poller($http, $interval){
var data = {
'newData': {
'one' : '',
'key' : ''
},
'fetchCount': 0
};

var getData = function() {
data.fetchCount += 1;
$http.get('http://echo.jsontest.com/key/value/one/two')
.then(function(response){
data.newData = response.data;
});
};

var loopGetData = function() {
$interval(getData, 5000);
};

loopGetData();

return{
data: data,
};
});

app.controller('ListController', function($scope, Poller){
$scope.activities = {'one' : '', 'key' : ''};

$scope.Initialize = function () {
$scope.$watch(function () { return Poller.data.newData; },
function(newValue, oldValue) {
if (newValue !== oldValue) {
$scope.activities = newValue;
}
});
};

$scope.Initialize();
});

app.controller('CountController', function($scope, Poller){
$scope.fetchCount = 0;

$scope.Initialize = function () {
$scope.$watch(function () { return Poller.data.fetchCount; },
function(newValue, oldValue) {
if (newValue !== oldValue) {
$scope.fetchCount = newValue;
}
});
};

$scope.Initialize();
});

关于javascript - 在 Angular 中存储和使用定期更新的数据的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28175429/

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