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

时间:2017-05-25 19:10:42

标签: windows angular typescript ionic2 storage

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

file home.html

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 home.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();
      }
    );
   }
 }

file places.service.ts

{{1}}

1 个答案:

答案 0 :(得分:1)

问题在于,在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);

}