繁体   English   中英

离子应用程序错误:array.push()不是函数

[英]Ionic application error: array.push() is not a function

我创建了一个具有控制器和工厂的应用程序。 我在工厂内部有一个数组,希望将元素的id推送到此数组。 但是,当我尝试将元素推送到数组时,出现一个错误

“ favorites.push不是函数”

您可以在下面找到我的控制器和工厂。 感谢您的阅读: 工厂:

.factory('favoriteFactory',['$resource', 'baseURL','$localStorage', function ($resource, baseURL, $localStorage) {
            var favFac = {};
            var favorites = $localStorage.get('favorites', []);
          favFac.addFavorites = function (index) {
            for(var i=0; i<favorites.length; i++){
              if(favorites[i].id == index)
                return
            }
              favorites.push({id: index});
              $localStorage.storeObject('favorites',favorites)
          }
          favFac.deleteFromFavorites = function (index) {
            for (var i = 0; i < favorites.length; i++) {
              if (favorites[i].id == index) {
                favorites.splice(i, 1);
              }
            }
            $localStorage.storeObject('favorites', favorites)
          };

          favFac.getFavorites = function () {
            return $localStorage.getObject('favorites',[]);
          };
          return favFac
        }])

控制器:

    .controller('MenuController', ['$scope', 'menuFactory', 'favoriteFactory','baseURL', '$ionicListDelegate', 'dishes', '$localStorage',
         function($scope, menuFactory,favoriteFactory, baseURL, $ionicListDelegate, dishes, $localStorage) {


        $scope.baseURL = baseURL;
        $scope.tab = 1;
        $scope.filtText = '';
        $scope.showDetails = false;
        $scope.showMenu = true;
        $scope.message = "Loading ...";
        $scope.addFavorite = function (index) {
          console.log("index:" +index);
          favoriteFactory.addFavorites(index);
          $ionicListDelegate.closeOptionButtons();

        };
        $scope.dishes = dishes;

            $scope.select = function(setTab) {
              $scope.tab = setTab;

              if (setTab === 2) {
                $scope.filtText = "appetizer";
              }
              else if (setTab === 3) {
                $scope.filtText = "mains";
              }
              else if (setTab === 4) {
                $scope.filtText = "dessert";
              }
              else {
                $scope.filtText = "";
              }
                };
   $scope.isSelected = function (checkTab) {
      return ($scope.tab === checkTab);
    };

    $scope.toggleDetails = function() {
      $scope.showDetails = !$scope.showDetails;
    };
  }])

我假设您正在使用ngStorage get方法没有第二个参数。 因此,您尝试返回默认值[] (空数组)只是返回undefined ,然后您尝试将其推入undefined而不是数组。

ngStorage的源代码没有显示get第二个参数: https : //github.com/gsklee/ngStorage/blob/master/ngStorage.js

所以这行:

var favorites = $localStorage.get('favorites', []);

应该是这样的:

var favorites = $localStorage.get('favorites') || [];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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