我正在尝试在我的应用程序中的服务中使用角度局部存储模块(https://github.com/grevory/angular-local-storage),版本0.2.2(根据bower)。当我在服务中调用它时,我似乎遇到了问题,但是当我把它放在控制器中时它工作正常。
我的配置如下:
angular.module('myApp', [ 'LocalStorageModule' ])
.config(function (localStorageServiceProvider) {
localStorageServiceProvider
.setPrefix('test')
.setStorageType('localStorage');
})...
然后在我的服务中,我有这样的(简化,用于测试目的):
angular.module('myApp')
.service('UserService', [ 'localStorageService',
function(localStorageService) {
return {
save: function() {
localStorageService.set('user', 'me');
}
};
}]);
此代码产生错误:
TypeError:localStorageService.set不是函数
另一方面,如果我将完全相同的代码放入控制器(实际上是调用此服务的控制器),一切都按预期工作。角度本地存储是否在服务中不起作用?
提前致谢!
答案 0 :(得分:0)
通过微小的调整,它对我有用。请参阅下面的代码段。
angular.module('myApp', [ 'LocalStorageModule' ])
.config(function (localStorageServiceProvider) {
localStorageServiceProvider
.setPrefix('test')
.setStorageType('localStorage');
})
.service('UserService', [ 'localStorageService',
function(localStorageService) {
return {
save: function() {
localStorageService.set('user', 'me');
}
};
}])
.controller('MainCtrl', function($scope, UserService){
$scope.test = function(){
console.debug('save called');
UserService.save();
};
});

<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div ng-controller="MainCtrl">
<button ng-click="test()">Test</button>
</div>
<script type="text/ng-template" id="home.html">
Lorem ipsum
</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script src="bower_components/angular-local-storage/dist/angular-local-storage.js"></script>
</body>
</html>
&#13;