简体   繁体   中英

TypeError: Cannot read property 'unshift' of undefined AngularJS

I'm working on this new AngularJS project with ngStorage (localStorage) and not quite sure why I'm getting the message below. I get this whenever I click on my add button.

TypeError: Cannot read property 'unshift' of undefined AngularJS

Below is my code. Can someone explain why this error is occurring?

.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

.controller('HomeCtrl', function($scope, $localStorage, dataService, StorageService) {

    $scope.add = function (color) {
        StorageService.add(StorageService.favorites.unshift(dataService.colors.indexOf(color)));
        console.log(color);
      };
)};

What exactly are you trying to accomplish with the line in your controller:

StorageService.add(StorageService.favorites.unshift(dataService.colors.indexOf(color)));

I assume you want to call the add method of your service and pass it the value of color in dataService .

As metioned in the other answers your error comes from favorites not being defined in the return block of your service. But if you do define it you still won't be adding the color since unshift will return the new length of StorageService.favorites .

If my asumption is correct you'll probably want to do something like:

StorageService.add(dataService.colors.indexOf(color));

If you do need to "get" the favorites from your service, don't break your encapsulation by publishing $localStorage.favorites but use your getAll method to get the "favorites".

PS Also don't forget to check that dataService actually has a colors key or you have another potential null-pointer.

您可以像这样访问收藏夹数组(使用已经公开的getAll函数):

    StorageService.add(StorageService.getAll.unshift(dataService.colors.indexOf(color)));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM