Angular 2 如何从存储中删除列表项



如何通过单击按钮从存储(存储(中删除项目。元素通过输入输入并添加到页面中。新项目存储在存储中。现在的情况是这样的 - 通过单击按钮删除页面上的元素,当我更新页面时,它们仍然保留在原位。它们继续存放在某个地方。

文件主页.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>

文件主页.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();
      }
    );
   }
 }

问题是,在deletePlace(i)方法中,您正在从内存数组中删除该项目的位置,但没有更新存储。

服务中的deletePlace(...)方法不起作用,因为您将存储中的位置保存为数组,因此无法删除特定位置。

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

我会这样修复它:

在您的服务中,创建一个新方法,以便使用您对内存数组所做的更改来更新存储:

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

然后在组件代码中,在删除位置后调用该方法:

deletePlace(i) {
    console.log('delete');
    // Delete the place from the in memory array
    this.places.splice(i, 1);
    // Update the storage with the new list of places
    this.placesService.saveChanges(this.places);

}

相关内容

  • 没有找到相关文章

最新更新