Angularjs数据存储的最佳实践 [英] Angularjs Best Practice for Data Store
本文介绍了Angularjs数据存储的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的角度应用程序有2个控制器。我的问题是,当用户离开页面时,控制器不会保留数据。
My angular app have 2 controllers. My problem is that the controllers does not keep the data when the user navigates away from the page.
如何将我控制器上的选定数据存储到数据存储中,以便在其他控制器之间使用?
推荐答案
选项1 - 自定义服务
您可以使用专用的角度服务在控制器之间存储和共享数据(服务是单实例对象)
服务定义
app.service('commonService', function ($http) {
var info;
return {
getInfo: getInfo,
setInfo: setInfo
};
// .................
function getInfo() {
return info;
}
function setInfo(value) {
info = value;
}
});
在多个控制器中使用
app.controller("HomeController", function ($scope, commonService) {
$scope.setInfo = function(value){
commonService.setInfo(value);
};
});
app.controller("MyController", function ($scope, commonService) {
$scope.info = commonService.getInfo();
});
选项2 - html5 localStorage
您可以使用内置浏览器本地存储并随时随地存储数据
Option 2 - html5 localStorage
You can use the built-in browser local storage and store your data from anywhere
写作
$window.localStorage['my-data'] = 'hello world';
阅读
var data = $window.localStorage['my-data']
// ...
- 看看这个很棒的项目:
https://github.com/grevory/angular-local-storage - check out this awesome project: https://github.com/grevory/angular-local-storage
如果你需要在不同用户之间保存数据,你应该把它保存在服务器的某个地方side(db / cache)
If you need to persist data among different users, you should save it somewhere in the server side (db / cache)
function getProfile() {
return $http.get(commonService.baseApi + '/api/profile/');
}
function updateProfile(data) {
var json = angular.toJson(data);
return $http.post(commonService.baseApi + '/api/profile/', json);
}
这篇关于Angularjs数据存储的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文