首页 > 解决方案 > 将带有布尔值的对象 (json) 添加到离子存储 (ionic 4)

问题描述

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

我希望能够存储尽可能多的收藏(按房子资格),而其他都是正常的收藏(红心)。我向您展示一些代码并更好地解释它。

搜索.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用于普通收藏夹。

我可以轻松地添加和删除它,但我想设置一个限制,我希望只有一个对象可以拥有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>

标签: angularionic4ionic-storage

解决方案


我做了一个 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;
          });
        }
      })

推荐阅读