Ionic 2 Storage中删除数组指定id元素的问题求助
Got it, let's break down why your current approach isn't working and fix it properly.
The Problem with Your Current remove Method
The error "3 used as a key, but it is not a string" happens because storage.remove() is designed to delete an entire key-value pair from Ionic Storage. Right now, you're storing all your todos under a single key 'todos' (as an array), not storing each todo as an individual key (like using the todo's id as the key). So passing the numeric id directly to remove() doesn't make sense here—it's trying to delete a key named 3, which doesn't exist, and Storage requires keys to be strings anyway.
The Correct Approach
Since all todos are stored in one array under the 'todos' key, you need to:
- Fetch the full array of todos from Storage
- Filter out the todo with the target id
- Save the updated array back to Storage
Updated DataProvider Code
Here's the corrected remove method, using async/await for cleaner asynchronous code:
import { Injectable } from '@angular/core'; import { Storage } from '@ionic/storage'; @Injectable() export class DataProvider { constructor(public storage: Storage) { console.log('Hello DataProvider Provider'); } getData() { return this.storage.get('todos'); } save(data){ return this.storage.set('todos', data); // Added return to handle promise callbacks } async remove(id: number) { console.log("Removing data ID:", id); // Get current todos (fallback to empty array if none exist) const todos = await this.storage.get('todos') || []; // Filter out the todo with the matching id const updatedTodos = todos.filter(todo => todo.id !== id); // Save the updated array back to Storage await this.storage.set('todos', updatedTodos); return updatedTodos; // Optional: return the updated list for component use } }
If you prefer using Promises instead of async/await, here's the alternative version:
remove(id: number) { console.log("Removing data ID:", id); return this.storage.get('todos') .then(todos => { // If no todos exist, return empty array if (!todos) return []; // Filter out the target todo const updatedTodos = todos.filter(todo => todo.id !== id); // Save the updated array return this.storage.set('todos', updatedTodos); }) .catch(error => { console.error('Error removing todo:', error); throw error; // Re-throw to let the caller handle the error }); }
Key Notes
- Always handle the case where
todosmight benull(if nothing was stored yet) by using|| []to fallback to an empty array. - Use strict inequality (
!==) when comparing ids to avoid issues with type coercion (since your ids are numbers). - Adding
returnstatements to your Storage methods lets you handle success/error states in the components that useDataProvider.
内容的提问来源于stack exchange,提问作者Sujan Gainju

