互換的青春
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);
}
}
}
添加回答
舉報
0/150
提交
取消