我正在为我公司几周后推出的新品牌创建一个新的多用途网站。我们使用 WordPress 后端并通过 WP REST API,现在能够解耦系统并为我们的前端和中间件应用程序使用 NodeJS/Express/AngularJS。
目前,当我加载登陆页面时,会向 WordPress 发出 HTTP GET 请求,以获取我们首页的所有相关帖子。然后,该数据被传递到服务以跨 Controller 使用。
所以,初始设置是这样的:
登陆 Controller
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;
}
};
}
现在,当用户点击登陆页面上的帖子时,她会被带到一个页面,该页面显示在她点击的文章上,这是有效的。但是,如果她刷新此页面,所有数据都会消失。调用该服务会产生一个空对象。
后置 Controller
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']);
关于javascript - 如何在 AngularJS 中刷新时保留服务中的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36204281/