我有一个这样的对象数组,当我单击“删除收藏夹”按钮时,我想从本地存储中删除某个元素。我正在使用 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);
}
}
}
添加回答
举报
0/150
提交
取消