Angular:如何避免在本地存储中重复输入

时间:2019-07-13 19:19:59

标签: angular typescript angular-local-storage

当我单击心脏按钮时,该行中的数据将存储在本地存储中,但我希望存储在本地存储中的数据是唯一的,因为当我单击同一行两次时,会在本地存储中创建重复的条目。 / p>

我已经附上了本地存储的屏幕快照,您可以看到分支的重复条目存储在本地存储中。

这是我的代码的链接 https://stackblitz.com/edit/angular-ofvnz3?file=src%2Fapp%2Fhome%2Fhome.component.html

,但是由于某些导入错误,您无法运行它。请解决它。

1 个答案:

答案 0 :(得分:2)

在您的activeskill函数中,...将元素(传递给该函数的元素)推入value数组中,而不检查它是否已经存在...因此重复;要解决此问题,请在推送之前检查value数组中是否已存在该值;

相关的 TS

myFavArray: PeriodicElement[] = [];

  constructor() {
    if (localStorage.getItem('fav') == '' || localStorage.getItem('fav') == null) {
    } else {
      this.myFavArray = JSON.parse(localStorage.getItem('fav'));
      console.log('from localStorage', this.myFavArray);
    }
  }
  activeSkill(element) {
    let checkExists: boolean = false;
    for (var i = 0; i < this.myFavArray.length; i++) {
      if (element.position == this.myFavArray[i].position) {
        checkExists = true;
      }
    }
    if (checkExists == false) {
      this.myFavArray.push(element);
    }
    localStorage.setItem('fav', JSON.stringify(this.myFavArray));
  }

相关的 HTML

<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">

    <!--- Note that these columns can be defined in any order.
        The actual rendered columns are set as a property on the row definition" -->

    <!-- Position Column -->
    <ng-container matColumnDef="position">
        <th mat-header-cell *matHeaderCellDef> No. </th>
        <td mat-cell *matCellDef="let element">
            <button  (click)="activeSkill(element)" mat-icon-button>
    <mat-icon aria-label="Heart">favorite</mat-icon>
 </button>

      {{element.position}} </td>
  </ng-container>

  <!-- Name Column -->
  <ng-container matColumnDef="name">
    <th mat-header-cell *matHeaderCellDef> Name </th>
    <td mat-cell *matCellDef="let element"> {{element.name}} </td>
  </ng-container>

  <!-- Weight Column -->
  <ng-container matColumnDef="weight">
    <th mat-header-cell *matHeaderCellDef> Weight </th>
    <td mat-cell *matCellDef="let element"> {{element.weight}} </td>
  </ng-container>

  <!-- Symbol Column -->
  <ng-container matColumnDef="symbol">
    <th mat-header-cell *matHeaderCellDef> Symbol </th>
    <td mat-cell *matCellDef="let element"> {{element.symbol}} </td>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>

可验证的最低complete stackblitz here