如何使用 angularjs 在本地存储中保存 json 响应?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25397908/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to save json response in local storage using angularjs?
提问by Anita Mehta
I have api which return json response and I want to store that json response in localstorage to use that response in my another html page using angularjs.
我有返回 json 响应的 api,我想将该 json 响应存储在 localstorage 中,以便在使用 angularjs 的另一个 html 页面中使用该响应。
Here is my code which return json response....
这是我返回json响应的代码....
QAApp.controller('SearchCtrl', function ($scope, $http, $location) {
$scope.search = function (searchtag) {
var request = $http({
method: 'GET',
url: server + 'api/question/tagged/' + searchtag,
});
request.success(function(data, status, headers, config) {
console.log(data);
$scope.qa = data;
});
}
});
Please tell me how can I store it...
请告诉我如何保存它...
回答by Rajesh Manilal
On your request.success(),use
在您的 request.success() 上,使用
window.localStorage['storageName'] = angular.toJson(data);
Then you can access the data in localstorage by
然后你可以通过访问localstorage中的数据
var accessData = window.localStorage['storageName'];
回答by Narek Mamikonyan
I want to suggest this one because I used it and it works stable https://github.com/gsklee/ngStorage.
我想推荐这个,因为我用过它并且它工作稳定https://github.com/gsklee/ngStorage。
After downloading and attaching it to your project you should add it as a dependency
下载并将其附加到您的项目后,您应该将其添加为依赖项
QAApp.controller('SearchCtrl', function ($scope, $http, $location,$localStorage) {
$scope.search = function (searchtag) {
var request = $http({
method: 'GET',
url: server + 'api/question/tagged/' + searchtag,
});
request.success(function(data, status, headers, config) {
$localStorage.qa = datal
$scope.qa = data;
});
}
});
回答by Mihail Malohvey
$scope.Save = angular.toJson(data); //Save to storage
sessionStorage.setItem('blablabla',$scope.Save);
localStorage.setItem('blablabla', $scope.Save);
$scope.DataFromJson = JSON.parse(sessionStorage["blablabla"]); //Get from storage
$scope.DataFromJson = JSON.parse(localStorage["blablabla"]);
回答by GregL
I recommend using the angular-local-storagemodule on GitHub.
我建议使用GitHub 上的angular-local-storage模块。
回答by Manish Nakar
/* To retrive json from localStorage */
/* 从localStorage 检索json */
var user = angular.fromJson($window.localStorage['md-user']);
/* To store json in loacalStorage */
/* 将 json 存储在 loacalStorage */
$window.localStorage['md-user'] = angular.toJson(user);
回答by Rejneesh Raghunath
To store
储藏
$scope.storeItem = function() {
sessionStorage.setItem('item', angular.toJson($scope.selectedItem));
}
To retrieve
检索
$scope.retrieve = function() {
$scope.selectedItem = JSON.parse(sessionStorage.getItem('item'));
}

