我正在使用ngStorage(localStorage)处理这个新的AngularJS项目,但不太清楚为什么我会收到下面的消息。每当我点击我的添加按钮时,我会得到这个。TypeError:无法读取未定义AngularJS的属性'unshift'
TypeError: Cannot read property 'unshift' of undefined AngularJS
以下是我的代码。有人可以解释为什么这个错误发生?
.factory ('StorageService', function($localStorage) {
$localStorage = $localStorage.$default({
favorites: []
});
var _getAll = function() {
return $localStorage.favorites;
};
var _add = function (color) {
$localStorage.favorites.unshift(color);
}
var _remove = function (color) {
$localStorage.favorites.splice(index, 1);
}
return {
getAll: _getAll,
add: _add,
remove: _remove
};
})
控制器
.controller('HomeCtrl', function($scope, $localStorage, dataService, StorageService) {
$scope.add = function (color) {
StorageService.add(StorageService.favorites.unshift(dataService.colors.indexOf(color)));
console.log(color);
};
)};
StorageService没有名为favorites的属性..将它添加到返回对象。 –
这是因为localStorage.favorites不存在。 –
StorageService仅公开什么返回(GETALL,添加,删除) – sam1188