我正在学习Angular,我将LocalStorage
服务定义为:
.service('LocalStorage', function() {
var self = this;
this.localStorageAvailable = function() {
return typeof (Storage) !== "undefined";
};
this.set = function(key, value) {
if (!self.localStorageAvailable()) return;
localStorage.setItem(key, JSON.stringify(value));
};
this.get = function(key, defaultValue) {
if (!self.localStorageAvailable()) return defaultValue;
return JSON.parse(localStorage.getItem(key));
};
})
然后我想创建另一个使用我刚刚定义的LocalStorage
服务的服务,但它给出了:
错误:$ LocalStorage是udefined。
.service('FilterSvc', ['LocalStorage', function ($LocalStorage) {
var self = this;
var key = "Settings";
this.LoadSettings = function (universeCode) {
if ($LocalStorage.get(key, "") === "") {
////load setting, otherwise reuse
var result = "aaa";
this.set(key, result);
}
};
}]);
有人可以帮忙吗?
答案 0 :(得分:1)
您应该从变量$ LocalStorage
中删除 $答案 1 :(得分:0)
使用self
var self = this;
然后调用下面的函数
.........
self.servicefunction();
............
将this
替换为self
以获取所有功能;即使是经验丰富的程序员也是混淆的关键原因。
PS:您已声明var self = this
而未使用