我有带有用户身份验证的单页应用程序,在那里共享会话信息没有问题。
但是,我有一部分站点是静态页面,我只想在其中包含会话信息(登录用户或登录表单)。如何在两个应用程序之间共享会话信息?
我建议创建一个包装服务localStorage
或其他 api 来存储持久数据。这是一个使用localStorage
实现的示例。
这个实现是同步的,但如果我要使用websql
like 甚至 server db,那么我会重构它以使用promises来返回存储对象。
控制器
var demo = angular.module('demo', [ 'appStorage' ]);
demo.controller('AppStorageController', [ '$scope', 'appStorage',
function($scope, appStorage) {
appStorage('MyAppStorage', 'myAppStorage', $scope);
} ]);
HTML
<div ng-controller="AppStorageController">
<p>Local Storage: {{myAppStorage}}</p>
<p>
Username: <input type="text" ng-model="myAppStorage.username"></input>
</p>
<p>
Remember me: <input type="checkbox"
ng-model="myAppStorage.rememberMe"></input>
</p>
</div>
JS
angular.module('appStorage', []).factory('appStorage',
[ '$window', function($window) {
var appStorages = {};
var api = undefined;
if ($window.localStorage) {
api = {
set : function(name, value) {
$window.localStorage.setItem(name, JSON.stringify(value));
},
get : function(name) {
var str = $window.localStorage.getItem(name);
var val = {};
try {
val = str ? JSON.parse(str) : {};
}
catch (e) {
console.log('Parse error for localStorage ' + name);
}
return val;
},
clear : function() {
$window.localStorage.clear();
}
};
}
// possibly support other
if (!api) {
throw new Error('Could not find suitable storage');
}
return function(appName, property, scope) {
if (appName === undefined) {
throw new Error('appName is required');
}
var appStorage = appStorages[appName];
var update = function() {
api.set(appName, appStorage);
};
var clear = function() {
api.clear(appName);
};
if (!appStorage) {
appStorage = api.get(appName);
appStorages[appName] = appStorage;
update();
}
var bind = function(property, scope) {
scope[property] = appStorage;
scope.$watch(property, function() {
update();
}, true);
};
if (property !== undefined && scope !== undefined) {
bind(property, scope);
}
return {
get : function(name) {
return appStorage[name];
},
set : function(name, value) {
appStorage[name] = value;
update();
},
clear : clear
};
};
} ]);