項目中遇到一個問題,網上說的不清不楚的。app
一個列表頁面跳轉到另外一個詳細頁面傳遞一個id,要求刷新當前頁面時用剛纔跳轉過來的id再訪問一遍數據接口,這時須要把數據保存到localstorage中spa
一、新建一個service: localStorage.service.jslocalstorage
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 })()
二、在須要用到的地方配置並引入這個service,項目不一樣但原理都同樣,去查看angular關於service的文檔,不作說明code
三、使用對象
LocalStorageService.setLocalStorage("id",param.id);
LocalStorageService.getLocalStorage("id");