Removing an item from Storage in Angular 2: A simple guide

Is there a way to remove items from storage by clicking on a button added through input and stored in the page? Although elements are deleted from the page, they seem to be retained in storage even after refreshing the page.

file home.html

<ion-list>
<ion-item *ngFor="let place of places ; let i  = index" 
  (click)="onOpenPlace(place)">{{ place.title }}
</ion-item>
  <button ion-button color="danger" (click)="deletePlace(i)">Delete</button>
</ion-list>

file home.ts

import { Component } from '@angular/core';
import { Storage } from '@ionic/storage';          /*** does not work ***/

import { ModalController, NavController } from 'ionic-angular';
import { NewPlacePage } from "../new-place/new-place";
import { PlacePage } from "../place/place";
import { PlacesService } from "../../services/places.service";
import { Place } from "../../model/place.model";

@Component({
    selector: 'page-home',
    templateUrl: 'home.html'
})
 export class HomePage {
  places: {title: string}[] = [];

  constructor(
    private storage: Storage,
    public navCtrl: NavController,
    private placesService: PlacesService,
    private modalCtrl: ModalController) {

   }

    ionViewWillEnter() {
      this.placesService.getPlaces()
        .then(
      (places) => this.places = places
    );
   }

    onLoadNewPlace() {
      this.navCtrl.push(NewPlacePage);
   }

    onOpenPlace(place: Place) {
      this.modalCtrl.create(PlacePage, place).present();
   }

    deletePlace(i){                               /*** does not work ***/
      console.log('delete') 
        this.places.splice(i, 1);
   }
}   

file places.service.ts

import { Storage } from '@ionic/storage';          /*** does not work ***/
import { Injectable } from '@angular/core';
import { Place } from '../model/place.model';

@Injectable()
   export class PlacesService {
     private places: Place[] = [];

   constructor ( private storage: Storage) {}

   addPlace(place: Place) {
     this.places.push(place);
     this.storage.set('places', this.places);
}

   deletePlace(place: Place){                 /*** does not work ***/
     this.storage.remove('places');
}

   getPlaces() {
     return  this.storage.get('places')
       .then(
     (places) => {
       this.places = places == null ? [] : places;
       return this.places.slice();
      }
    );
   }
 }

Answer №1

The issue lies in the deletePlace(i) method, where you are successfully removing an item from your array of places stored in memory, but failing to update the storage accordingly.

Since your service saves places as an array in storage, just deleting a place does not work with the current deletePlace(...) implementation.

deletePlace(place: Place) {
    this.storage.remove('places');
}

To resolve this, consider implementing the following:

Create a new method within your service to update the storage whenever changes are made to the in-memory array:

saveChanges(places: Array<Place>) {
     this.places = places;
     this.storage.set('places', this.places);
}

Then, within your component code, remember to call this method after removing a place:

deletePlace(i) {
    console.log('delete');

    // Remove the place from the array stored in memory
    this.places.splice(i, 1);

    // Update the storage with the revised list of places
    this.placesService.saveChanges(this.places);

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Select the location for rendering the application within the root HTML using Single-SPA

I am strategizing to utilize the single-SPA framework alongside angular in order to construct a microfrontend architecture for a website. The current setup of the website is based on a legacy monolith structure, but we are aiming to transition it into a mi ...

The issue of sending a POST request with form-data body parameters is not functioning as expected in Angular 2

I have successfully sent a file and other parameters in the body with type 'form-data' using Postman. Now, I am trying to achieve the same functionality in Angular 2. Please refer to the screenshot of the request made in Postman: https://i.stack. ...

Troubleshooting: Angular.js error when Typescript class constructor returns undefined

I'm currently trying to create a simple TypeScript class, however I keep encountering an error stating this is undefined in the constructor. Class: class MyNewClass { items: string; constructor(){ this.items = 'items'; ...

Using Angular2 to Inject a Service into Another Service

I'm having trouble locating my mistake. app.module.ts ... providers: [ValidateService,AuthService] ... In the register.component.ts file, I perform the following actions: import {AuthService} from '../../services/auth.service' ...

Challenge with Angular *ngFor: Struggling to Access Previous Elements

In my angular and node application, I am using socket.io. When a user joins the room, they can see their username in the user list. If another user joins, the first user can see both usernames but the new user can only see their own. This pattern continues ...

The upcoming construction of 'pages/404' page will not permit the use of getInitialProps or getServerSideProps, however, these methods are not already implemented in my code

Despite my efforts to search for a solution, I have not found anyone facing the same issue as me. When I execute next build, an error occurs stating that I cannot use getInitalProps/getServerSideProps, even though these methods are not used in my 404.tsx f ...

Swapping elements with drag and drop in Angular 7

I'm experimenting with the new Angular 7 CDK Drag and drop feature to rearrange a list of items. However, I haven't been able to find an option to swap elements - most of the examples focus on sorting elements instead. Check out this example on ...

When I attempt to add a todo item by clicking, the Url value is displayed as "undefined"

I am facing an issue with my household app where, upon clicking the button to navigate to the addtodo page, the URL specific to the user's house is getting lost. This results in the todolist being stored as undefined on Firebase instead of under the c ...

What is the purpose of the .default() method being added to the class constructor in transpiled Typescript code

In TypeScript, I have the following code snippet to create an instance of ConnectRoles Middleware in Express: let user = new ConnectRoles(config); The middleware initialization is expected to be a simple call to a constructor. However, after transpiling, ...

Struggle between Angular and fundamental CSS principles

Upon following the steps below, I aim to achieve my desired grids: How to set auto-margin boxes in flexible-width design using CSS? The solution provided is effective when implemented outside of Angular. However, when inserted inside an Angular component ...

react useState fetch does not loop

Error: Unable to iterate over the response Welcome page: import React, {useState, useEffect} from 'react' import {Main} from './style' import {sendRequest} from './ajax/main' const Home:React.FC<any> = () => { co ...

Looking for Angular pre-observable solutions

In my application, I have been relying on the rxjs/Subject Observable object for its ability to effortlessly handle multiple subscribers without needing modifications in other components. However, I have encountered a new use case that this object may not ...

Invalid file name detected during the download process

Below is the Javascript code I currently use to download a pdf: var link = document.createElement('a'); link.innerHTML = 'Download PDF file'; link.download = "Report.pdf"; link.href = 'data:application/octet-stream;base64 ...

The attempt to establish a connection with the Pipe Client using CreateFile fails due to Error 231,

I am currently working on enabling communication between two DLLs. One DLL acts as a Pipe Server, staying active throughout the program's runtime, while the other functions as a Pipe Client, connecting and disconnecting based on specific circumstances ...

Embracing Angular 9 Ivy results in encountering errors

After updating my app to Angular 9, I encountered an issue with Ivy where I receive the error error NG6002: The error logs are as follows - 32 export class FooterModule { } ~~~~~~~~~~~~ src/app/core/ncpapp.core.module.ts:30:14 - error NG6002: ...

Issue detected in the console: Angular and Express code linked with status code 200 displaying an error

I am attempting to delete data along with an image connected to that data via an image Id using a get route (since the delete route didn't work out for me). The data is successfully being deleted, but I keep receiving a 200 OK response followed by an ...

Error: Attempting to call a function on a type that does not have a callable signature. The type 'Number' does not support calling functions

Previous inquiries on this topic have left me with unanswered questions. As a newcomer, I've been exploring TypeScript's import and export functionality. Below is the code snippet I've come up with. Your feedback would be greatly appreciate ...

Webpack cannot find the specified module extension

I am facing a challenge with my project that involves both express and Angular. In this discussion, I will focus only on the express side. https://i.sstatic.net/C1blt.png When importing custom modules on the server side, I use the following syntax: impo ...

An issue occurs with Material Dialog getting stuck when it is triggered by clicking on a Leaflet

I'm currently working on a project that involves using a map with ngx-leaflet. When a user clicks on a marker, I want to display a Dialog from Angular Material. Although the Dialog opens successfully, when I click the close button, it reopens and the ...

Struggling to access the 'payload' property of an undefined object? In TypeScript, you can easily bind and access JSON objects using *ngFor directive

I've been attempting to retrieve highscores from the server using node angular and making an http request. Although I successfully obtain the JSON file from the server, I am encountering difficulty accessing the fields for processing in the *ngFor lo ...