Angular页面刷新保存变量数据,运用localstorage

项目中遇到一个问题,网上说的不清不楚的。

一个列表页面跳转到另一个详细页面传递一个id,要求刷新当前页面时用刚才跳转过来的id再访问一遍数据接口,这时需要把数据保存到localstorage中

1、新建一个service: localStorage.service.js

 1 (function() {
 2     'use strict';
 3 
 4     angular.module('app').factory('LocalStorageService',['$window',function($window){
 5           var service = {};
 6 
 7           service.setLocalStorage = setLocalStorage;
 8           service.getLocalStorage = getLocalStorage;
 9           service.setLocalStorageObject = setLocalStorageObject;
10           service.getLocalStorageObject = getLocalStorageObject;
11 
12           function setLocalStorage(key,value){
13             $window.localStorage[key]=value;
14           }
15           
16           function getLocalStorage(key,defaultValue){
17             return  $window.localStorage[key] || defaultValue;
18           }
19                  //存储对象,以JSON格式存储
20           function setLocalStorageObject(key,value){
21             $window.localStorage[key]=JSON.stringify(value);
22           }
23                 //读取对象
24           function getLocalStorageObject(key) {
25             return JSON.parse($window.localStorage[key] || '{}');
26           }
27 
28           return service;
29         }]);
30 })()

2、在需要用到的地方配置并引入这个service,项目不同但原理都一样,去查看angular关于service的文档,不做说明

3、使用

LocalStorageService.setLocalStorage("id",param.id);
LocalStorageService.getLocalStorage("id");
原文地址:https://www.cnblogs.com/oldcook/p/6795006.html