如何添加和删除本地存储中的特定数据? [英] How can I add and remove specific data in local storage?

查看:242
本文介绍了如何添加和删除本地存储中的特定数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始学习Angular,我正在尝试使用github API创建github搜索应用,但本地存储存在一些问题。我有一个添加到收藏夹按钮,用于将个人资料固定到页面。固定后,应显示删除收藏夹按钮,而不是添加到收藏夹按钮,并且应删除个人资料。我以为可以通过在本地存储中添加和删除配置文件来做到这一点。我有一个用户变量,当用户在搜索栏中键入用户名时,它将个人资料信息作为对象保存。然后,我将这些数据传递到本地存储,并获取所有本地存储数据以使其成为数组,以便可以使用* ngFor进行显示。问题是当我固定配置文件时,无法从页面中永久删除特定的配置文件。我只能暂时删除固定的个人资料。我已经处理了两天的问题,我已经分享了我到目前为止所做的部分。紫色区域是固定配置文件的显示位置。

I started learning Angular recently, I'm trying to make a github search app with the github api but I have some problems with local storage. I have an add to favorite button for pin the profile to the page. When it's pinned remove favorite button should be appear instead of add to favorite button and it should be remove the profile. I thought I could do this with adding and removing profiles from local storage. I have an user variable which holds the profile info as an object when the user types username in the search bar. Then I'm passing this data to local storage and take all the local storage data to make it an array so I can display it with *ngFor. The problem is when I pin the profile, I can't remove permanently specific profile from the page. I can only delete pinned profiles temporarily. I'm dealing with this problem for two days, I have shared the part what I did until now. The purple area is where the pinned profiles are shown.

home.component.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 style="background-color: rgb(106, 106, 170);" *ngFor="let item of display">
  <button (click)="consoleLog()">consoleLog</button>
  <p>Username: {{item.login}}</p>
  <p>Location: {{item.location}}</p>
  <p>ID: {{item.id}}</p>
  <button (click)="localStorage(item.id)">Add to favoriteeee</button>
  <button (click)="removeLocal(item.id)" class="viewProfileButton">Remove Favorite</button>
</div>
<button (click)="consoleLog()" class="viewProfileButton">Console Log</button>
<router-outlet></router-outlet> 

home.component.ts:

import { Component, OnInit, Input } from '@angular/core';
import { HttpService } from '../http.service';
import { ProfileComponent } from './profile/profile.component';
import { JsonPipe } from '@angular/common';
import { bindCallback } from 'rxjs';
import { FormArray } from '@angular/forms';

@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.idString = JSON.stringify(id);
    localStorage.setItem(this.idString, JSON.stringify(this.user));
    this.display = Object.values(localStorage).map((val: any) => JSON.parse(val));
    console.log(Object.values(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);
        localStorage.removeItem(this.display[i].id);
      }
    }
  }

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

}


推荐答案

in component.ts

in component.ts

let item = 1;
`
localStorage.setItem('itemName',Item);
const getItem = localStorage.getItem('itemName')

因此常量getItem将具有您的价值。您可以对数组执行相同操作

so constant getItem will have your value. you can do the same with an array

这篇关于如何添加和删除本地存储中的特定数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆