Ionic中向$localStorage数组追加对象报错:push不是函数
Let's break down why this error is happening and fix it step by step—this is a common issue when working with arrays and $localStorage in AngularJS.
The error tells us directly: $scope.sTempLoc isn't an array when you try to call push() on it. Let's fix that and make sure we append objects without overwriting existing data.
1. Correctly Initialize Your Array
Right now, you're resetting $scope.sTempLoc = []; every time your saveWfhLocation function runs, which wipes out any existing data. Worse, if you're pulling data from $localStorage later and that data isn't properly parsed as an array, you'll end up with a non-array value that can't use push().
Instead, initialize the array once when the controller loads, pulling from $localStorage first (or defaulting to an empty array):
// Initialize when the controller loads, not inside the save function $scope.sTempLoc = JSON.parse($localStorage.savedWfhLocations) || [];
JSON.parse()converts the string stored in$localStorageback to a JavaScript array (since$localStorageonly stores strings).- The
|| []ensures we get a clean empty array if there's no existing data in$localStorage.
2. Append the Object & Persist to $localStorage
Now inside your saveWfhLocation function, you can safely append your location object and save the updated array back to $localStorage:
$scope.saveWfhLocation = function (){ // Build your location object from your current details const newWfhLocation = { uCuWfhLocNam: $scope.uCurLocDtls.uCuWfhLocNam, // Add any other properties you need here (e.g., coordinates, timestamps) }; // Append the new object to the array (this will work now that sTempLoc is an array!) $scope.sTempLoc.push(newWfhLocation); // Save the updated array back to $localStorage (convert to string first) $localStorage.savedWfhLocations = JSON.stringify($scope.sTempLoc); // Optional: Add success feedback or navigation logic here $ionicPopup.alert({ title: 'Success', template: 'Location saved!' }); };
3. Double-Check for Common Mistakes
If you still run into issues, verify these points:
- Never store a single object directly in
$localStorage.savedWfhLocations—always store the full array. - Make sure you aren't overwriting
$scope.sTempLocwith a non-array value elsewhere in your code. - Confirm that any existing data in
$localStorageis valid JSON (you can check this in your browser's dev tools under Application > Local Storage).
内容的提问来源于stack exchange,提问作者Daniel Smith

