为了账号安全,请及时绑定邮箱和手机立即绑定

如何访问本地存储中某些元素的密钥?

如何访问本地存储中某些元素的密钥?

互换的青春 2022-12-18 16:19:07
我有一个这样的对象数组,当我单击“删除收藏夹”按钮时,我想从本地存储中删除某个元素。我正在使用 removeLocal() 函数从页面中删除,但它只从页面中删除,而不是从本地存储中删除。我想把它都删除。我在分配本地存储密钥时生成随机数。有没有办法访问此密钥并删除该项目?HTML:<input type="text" [(ngModel)]="profile" (ngModelChange)="detectChange($event)" (keyup)="findProfile()"  placeholder="Enter the username..." class="input"><div style="background-color: lightslategrey;">  <ng-template [ngIf]="profile !== '' && user">    <img [src]="user.avatar_url" alt="" class="userAvatar">    <p>Username: {{user.login}}</p>    <p>Location: {{user.location}}</p>    <p>E-mail: {{user.email}}</p>    <p>Blog Link: {{user.blog}}</p>    <p>Member Since: {{user.created_at}}</p>    <button [routerLink]="['', user.login.toLowerCase(), user.id ]" class="viewProfileButton" a>View      Profile</button><br>    <button (click)="localStorage()" class="viewProfileButton">Add to Favorite</button>  </ng-template></div><div *ngIf="closeDiv">  <div style="background-color: rgb(106, 106, 170);" *ngFor="let item of display">    <p>Username: {{item.login}}</p>    <p>Location: {{item.location}}</p>    <p>ID: {{item.id}}</p>    <button (click)="removeLocal(item.id)" class="viewProfileButton">Remove Favorite</button>  </div></div><button (click)="consoleLog()" class="viewProfileButton">Console Log</button><router-outlet></router-outlet>
查看完整描述

1 回答

?
宝慕林4294392

TA贡献2021条经验 获得超8个赞

添加对localStorage.removeItem(key)removeLocal 函数的调用。当然,您需要将随机密钥存储在某个地方,否则您将不得不集成此解决方案来解析它们。


  removeLocal(id: any, key: string) {

    for (let i = 0; i < this.display.length; i++) {

      if (this.display[i].id === id) {

        this.display.splice(i, 1);

        localStorage.removeItem(key); // here

      }

    }

  }

编辑:在评论中进行对话后,可以简化此解决方案,通过storageKey在显示中存储一个变量来从函数头中删除一个变量。


  removeLocal(id: any) {

    for (let i = 0; i < this.display.length; i++) {

      if (this.display[i].id === id) {

        localStorage.removeItem(this.display[i].storageKey);

        this.display.splice(i, 1);

      }

    }

  }


查看完整回答
反对 回复 2022-12-18
  • 1 回答
  • 0 关注
  • 70 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号