Javascript 如何访问某些元素';什么是本地存储的关键?

Javascript 如何访问某些元素';什么是本地存储的关键?,javascript,angular,typescript,sorting,local-storage,Javascript,Angular,Typescript,Sorting,Local Storage,我有一个这样的对象数组,当我单击“删除收藏夹”按钮时,我想从本地存储中删除特定元素。我使用removeLocal()函数从页面中删除,但它只从页面中删除,而不是从本地存储中删除。我想同时删除它。我在分配本地存储密钥时生成随机数。是否有办法访问此密钥并删除该项 html: <input type="text" [(ngModel)]="profile" (ngModelChange)="detectChange($event)"

我有一个这样的对象数组,当我单击“删除收藏夹”按钮时,我想从本地存储中删除特定元素。我使用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>
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss'],
})
export class HomeComponent implements OnInit {
  user: any;
  profile: any;
  display: any;
  local: any;
  randomNumber: any;
  randomString: any;
  idString: any;
  keys: any;
  closeDiv: boolean = true;
  constructor(private userData: HttpService) {}

  ngOnInit() {
    this.display = Object.values(localStorage).map((val: any) => JSON.parse(val));
    console.log('ngOnInit Works', this.display);
  }

  findProfile() {
    this.userData.updateProfile(this.profile);
    this.userData.getUser().subscribe((result) => {
      this.user = result;
    });
  }

  localStorage(id: any) {
    this.randomNumber = Math.floor(Math.random() * 10000);
    this.randomString = this.randomNumber.toString();
    localStorage.setItem(this.randomString, JSON.stringify(this.user));
    this.display = Object.values(localStorage).map((val: any) => JSON.parse(val));
    console.log(this.display);
  }

  removeLocal(id: any) {
    for (let i = 0; i < this.display.length; i++) {
      if (this.display[i].id === id) {
        this.display.splice(i, 1);
      }
    }
  }

  detectChange(ev: any) {
    ev.length > 0 ? (this.closeDiv = false) : (this.closeDiv = true);
  }

}

用户名:{{user.login}

位置:{{user.Location}

电子邮件:{{user.email}

博客链接:{{user.Blog}

成员自:{{user.created_at}

看法 个人资料
添加到收藏夹 用户名:{{item.login}

位置:{{item.Location}

ID:{{item.ID}

删除收藏夹 控制台日志
ts:

<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>
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss'],
})
export class HomeComponent implements OnInit {
  user: any;
  profile: any;
  display: any;
  local: any;
  randomNumber: any;
  randomString: any;
  idString: any;
  keys: any;
  closeDiv: boolean = true;
  constructor(private userData: HttpService) {}

  ngOnInit() {
    this.display = Object.values(localStorage).map((val: any) => JSON.parse(val));
    console.log('ngOnInit Works', this.display);
  }

  findProfile() {
    this.userData.updateProfile(this.profile);
    this.userData.getUser().subscribe((result) => {
      this.user = result;
    });
  }

  localStorage(id: any) {
    this.randomNumber = Math.floor(Math.random() * 10000);
    this.randomString = this.randomNumber.toString();
    localStorage.setItem(this.randomString, JSON.stringify(this.user));
    this.display = Object.values(localStorage).map((val: any) => JSON.parse(val));
    console.log(this.display);
  }

  removeLocal(id: any) {
    for (let i = 0; i < this.display.length; i++) {
      if (this.display[i].id === id) {
        this.display.splice(i, 1);
      }
    }
  }

  detectChange(ev: any) {
    ev.length > 0 ? (this.closeDiv = false) : (this.closeDiv = true);
  }

}
@组件({
选择器:“应用程序主页”,
templateUrl:“./home.component.html”,
样式URL:['./home.component.scss'],
})
导出类HomeComponent实现OnInit{
用户:任何;
简介:任何;
显示:任何;
本地:有;
随机数:任意;
随机字符串:任意;
idString:任何;
钥匙:任何;
closeDiv:boolean=true;
构造函数(私有用户数据:HttpService){}
恩戈尼尼特(){
this.display=Object.values(localStorage).map((val:any)=>JSON.parse(val));
log('ngOnInit Works',this.display);
}
findProfile(){
this.userData.updateProfile(this.profile);
this.userData.getUser().subscribe((结果)=>{
this.user=结果;
});
}
本地存储(id:any){
this.randomNumber=Math.floor(Math.random()*10000);
this.randomString=this.randomNumber.toString();
setItem(this.randomString,JSON.stringify(this.user));
this.display=Object.values(localStorage).map((val:any)=>JSON.parse(val));
console.log(this.display);
}
removeLocal(id:any){
for(设i=0;i0?(this.closeDiv=false):(this.closeDiv=true);
}
}

将调用
localStorage.removietem(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
      }
    }
  }

我试过了,但关键参数未定义。我想我应该从html发送参数,对吗?是的,但是在传入参数之前,需要将其存储在某个位置。类似于
this.user.storageKey=this.randomString
的内容,然后才能在localStorage中设置它,因此它必须位于
localStorage()
函数中。否则你就要放弃它们了。@DAktas我用第二个选项更新了我的解决方案,只是为了简化一些。