您的当前位置:首页正文

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

2022-03-26 来源:步旅网
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\LocalStorageService.getLocalStorage(\"id\");

因篇幅问题不能全部显示,请点此查看更多更全内容