[英]How to persist data in a service on refresh in AngularJS?
我正在为公司在几周内推出的新品牌创建一个新的多用途网站。 我们使用WordPress后端,并通过WP REST API,现在能够解耦系统,并为前端和中间件应用程序使用NodeJS / Express / AngularJS。
当前,当我加载登录页面时,对WordPress的HTTP GET请求是针对我们首页的所有相关帖子的。 然后,此数据将传递到服务,以供跨控制器使用。
因此,初始设置是这样的:
landingController
angular
.module('glossy')
.controller('LandingController', LandingController)
LandingController.$inject = ['featuredService', 'sharedPostsService'];
function LandingController(featuredService, sharedPostsService){
// Set up view model (vm) variables
var vm = this;
vm.featured = [];
// Call this function on state 'home' load
activate();
// Calls getFeatured function and prints to console
function activate(){
return getFeatured()
.then(function(){
console.log('GET Featured Posts');
});
}
// Calls the featuredService then stores response clientside for rendering
function getFeatured(){
return featuredService.getFeatured()
.then(function(data){
vm.featured = data;
sharedPostsService.setPosts(data);
return vm.featured;
});
}
}
HTTP请求工厂
angular
.module('glossy')
.factory('featuredService', featuredService)
featuredService.$inject = ['$http'];
function featuredService($http){
return {
getFeatured: getFeatured
};
// Performs HTTP request then calls success or error functions
function getFeatured(){
return $http.get('/api/posts')
.then(getFeaturedComplete)
.catch(getFeaturedFailed);
// Returns response data
function getFeaturedComplete(response){
return response.data;
}
// Prints error to console
function getFeaturedFailed(error) {
console.log('HTTP Request Failed for getFeatured: ' + error.data);
}
}
}
保留工厂数据的服务
angular
.module('glossy')
.factory('sharedPostsService', sharedPostsService)
function sharedPostsService(){
var listPosts = [];
return {
setPosts: function(posts){
listPosts = posts;
},
getPosts: function(){
return listPosts;
}
};
}
现在,当用户单击登录页面上的帖子时,她将被带到一个在其单击的文章上显示的页面,该页面将起作用。 但是,如果她刷新此页面,则所有数据均消失。 调用服务将导致一个空对象。
后置控制器
angular
.module('glossy')
.controller('PostController', PostController)
PostController.$inject = ['$window', '$filter', '$stateParams', 'sharedPostsService'];
function PostController($window, $filter, $stateParams, sharedPostsService){
var vm = this;
vm.postsList = sharedPostsService.getPosts();
vm.postTitle = $stateParams.title;
vm.thisPost = filterPosts();
function filterPosts() {
return $filter('filter')(vm.postsList, vm.postTitle);
};
}
我该如何设置以确保数据通过刷新保持不变? 我调查了使用localStorage的过程,但是发现的所有内容都涉及将数据字符串化并将其存储在键值对中?
任何帮助表示赞赏。
您不能使用服务将数据保留在页面刷新上。
如果数据很大,则使用数据库,否则使用sessionStorage
或localStorage
。
存储数据 :
window.localStorage['data'] = JSON.stringify(data);
检索数据 :
return angular.fromJson(window.localStorage['data']);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.