添加一个带有布尔值的 object (json) 到离子存储 (ionic 4)

Add an object (json) with a boolean to ionic storage (ionic 4)

我想在我的存储中添加一个特别的收藏,我可以将我想要的收藏数量添加到我的存储中,但我只想要 1 个是我最喜欢的! 有一个image强调你我的想法!

我希望能够存储最多一个收藏夹(由庄家限定),其他都是普通收藏夹(红心)。我给你看一些代码并更好地解释它。

search.page.ts

    getItems(ev) {
    this.loadFavorites();

    var val = ev.target.value;

    if (val && val.trim() != '') {
      this.storageService.getFavorites().then(favorites => {
        this.favorites = this.favorites.filter((favorite) => {
          return (favorite.adresse.toLowerCase().indexOf(val.toLowerCase()) > -1);
        });
      });
    }
  }

  @ViewChild('mylist') mylist: IonList;

  // CREATE
  addFavorite(adresse: string, lat: string, lon: string) {
    this.newFavorite.adresse = adresse.replace(/[, ]+/g, " ").trim()
    this.newFavorite.lat = lat
    this.newFavorite.lon = lon
    this.newFavorite.modified = false;
    this.newFavorite.id = Date.now();

    this.storageService.addFavorite(this.newFavorite).then(favorite => {
      this.newFavorite = <Favorite>{};
      console.log(this.newFavorite.adresse)
      this.showToast('Favorite added!');
      this.loadFavorites()
    });
  }

  addFavoriteHome(adresse: string, lat: string, lon: string) {
    this.newFavorite.adresse = adresse.replace(/[, ]+/g, " ").trim()
    this.newFavorite.lat = lat
    this.newFavorite.lon = lon
    this.newFavorite.modified = true;
    this.newFavorite.id = Date.now();

    this.storageService.addFavorite(this.newFavorite).then(favorite => {
      this.newFavorite = <Favorite>{};
      this.showToast('Favorite added!')
      this.loadFavorites()
    });

  }

你可以在这段代码上看到,当我添加一个新的收藏夹时,它添加 this.newFavorite.modified = true; 并且它是 false 用于普通收藏夹。

我可以轻松添加和删除它,但我想设置一个限制,我希望只有一个 object 可以有 this.newFavorite.modified = true;.

search.page.html

<ion-list mode="md" #mylist>
        <div *ngFor="let favorite of favorites">

            <ion-item mode="md">
                <ion-label text-wrap>
                    <p>{{favorite.modified}}</p>
                    <h3 routerLink="/home/{{favorite.adresse}}">{{ favorite.adresse | slice:0:30 }}...</h3>
                </ion-label>
                <img *ngIf="favorite.modified" (click)="addFavoriteHome(favorite)" src="../../assets/icon/home-full.svg" style="width: 35px;" alt="">
                <img *ngIf="!favorite.modified" (click)="addFavorite(favorite)" src="../../assets/icon/home.svg" style="width: 35px;" alt="">
                <ion-icon name="heart" (click)="deleteAlert(favorite)" end></ion-icon>
            </ion-item>
        </div>

    </ion-list>

我做了一个 forEach 方法来逐个更新所有收藏夹,并且有效!

     this.favorites.forEach((favorites, index) => {
        console.log(favorites)
        if (favorites.modified == true) {
          favorites.modified = false
          this.storageService.updateItem(favorites)
          this.storageService.getFavorites().then(favorites => {
            this.favorites = favorites;
          });
        }
      })