【问题标题】:How can I limit the local storage maximum item?如何限制本地存储最大项目?
【发布时间】:2020-11-24 05:11:00
【问题描述】:

我正在使用 Angular 中的 github api 构建 github 搜索应用程序。我需要限制本地存储可以占用的元素数量。如果限制存储元素数量超过 5 个,添加到收藏按钮应该不起作用或者它也会消失。我用这个[ngStyle]="{'display': display.length > 5 && 'none' }" 做到了,但这并不是我想要的。代码如下:

html:

  <input type="text" [(ngModel)]="profile" (ngModelChange)="detectChange($event)" (keyup)="findProfile()" class="input">

  <ng-template [ngIf]="profile !== '' && user">
    <div class="profileContainer">
      <div class="leftDetails">
        <img class="userAvatar" [src]="user.avatar_url" alt="User Avatar">
        <div>
          <button class="button" [routerLink]="['', user.login.toLowerCase(), user.id ]">View
            Profile</button>
          <button class="button" [ngStyle]="{'display': display.length > 5 && 'none' }" (click)="addLocal()">Add to
            Favorite</button>
        </div>
      </div>

      <div class="rightDetails">
        <p><span>Username: </span> {{user.login}}</p>
        <p><span>Location:</span> {{user.location}}</p>
        <p><span>E-mail:</span> {{user.email}}</p>
        <p><span>Blog Link:</span> {{user.blog}}</p>
        <p><span>Member Since:</span> {{user.created_at}}</p>
      </div>

    </div>
  </ng-template>

  <div *ngIf="closeDiv">
    <div class="profileContainer" *ngFor="let item of display">
      <div class="leftDetails">
        <img class="userAvatar" [src]="item.avatar_url" alt="User Avatar">
        <div>
          <button class="button" [routerLink]="['', item.login.toLowerCase(), item.id ]">View Profile</button><br>
          <button class="button" (click)="removeLocal(item.id,item.storageKey)">Remove Favorite</button>
        </div>
      </div>

      <div class="rightDetails">
        <p><span>Username:</span> {{item.login}}</p>
        <p><span>Location:</span> {{item.location}}</p>
        <p><span>E-Mail:</span> {{item.email}}</p>
        <p><span>Blog Link:</span> {{item.blog}}</p>
        <p><span>Member Since:</span> {{item.created_at}}</p>
      </div>
    </div>
  </div>
</div>

<button (click)="consoleLog()">CONSOLEEE</button>

<router-outlet></router-outlet>

ts:

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';
import { ArrayType } from '@angular/compiler';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss'],
})
export class HomeComponent implements OnInit {
  user: any;
  profile: any;
  display: any;
  randomNumber: number;
  randomString: string;
  closeDiv: boolean = true;
  isClicked: boolean = true;

  constructor(private userData: HttpService) {}

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

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

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

  public 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);
      }
    }
  }

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

【问题讨论】:

  • @pallavirichhariya 我添加了 html 代码。

标签: javascript angular typescript local-storage


【解决方案1】:

我不觉得在localStorage上使用map,只是你可以检查localstorage的长度并在HTML/模板端添加检查。

this.display = Object.values(localStorage).length;
<button class="button" *ngIf="display.length < 5">Add to           
Favorite</button>

【讨论】:

  • 我认为在 html 中也使用 display 来显示数据,因此使用了地图
  • @pallavirichhariya 是的,你是对的。我为长度分配了另一个变量。
  • @pallavirichhariya 可能是我不知道那个用例:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-03-04
  • 1970-01-01
  • 2010-12-27
  • 1970-01-01
  • 2021-05-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多