You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular开发GIF商店:如何避免本地存储添加重复GIF?

问题描述

我正在使用Angular开发一个GIF商店。页面带有搜索输入框,输入GIF名称后会调用Giphy搜索API返回对应GIF。同时我通过localStorage实现了用户存储区,保存的GIF是包含url和id的对象。现在需要实现:如果Giphy API返回的GIF已经存在于localStorage中,则不再将其添加到用户存储区。

相关代码

User-Gif.component.ts

从Giphy API获取GIF的方法

onSearchClick() : void {
    this.gs.searchGif(this.searchInput,this.defaultLimit).subscribe(res => {
      this.gifData = res.data;
    })
}

将GIF存储到localStorage的方法

addToStore(): void {
    let addGif= new Array<GifUrl>();
  
    this.gifData.forEach((i:any) => {
      addGif.unshift({
        id: i.id,
        url: i.images.original.url,
        date: new Date()
      })
      localStorage.setItem(this.searchInput.toUpperCase(),JSON.stringify(addGif));
   })
  
    this.getDataInStore();
    this.gifData = [];
    addGif=[];
    this.searchInput = '';
}

从localStorage获取GIF的方法

getDataInStore():void {
    this.gifUrl=[];
    if(Object.keys(localStorage)) {
      Object.keys(localStorage).forEach((key:string)=> {
       let keyData:any[] = JSON.parse(localStorage.getItem(key) || '')
        this.gifUrl.push(...keyData);
     })
    }
}

User-gif.html

<div class="userStore">
    <app-user-store [gifData]="gifUrl" (filteredData)="getFilteredData($event)" (sortedData)="sortByDate()"
        (resetSearch)="resetData()">
    </app-user-store>
</div>
解决方案

要实现重复GIF不添加的逻辑,核心是先收集localStorage中已存在的所有GIF的id,再在添加新GIF前做判断:

  1. 封装方法获取所有已存储的GIF ID集合
private getExistingGifIds(): Set<string> {
    const existingIds = new Set<string>();
    Object.keys(localStorage).forEach(key => {
        const storedGifs = JSON.parse(localStorage.getItem(key) || '[]');
        storedGifs.forEach((gif: any) => existingIds.add(gif.id));
    });
    return existingIds;
}
  1. 修改addToStore方法,添加重复判断并优化存储逻辑
addToStore(): void {
    const existingIds = this.getExistingGifIds();
    // 过滤出未存储过的GIF
    const newGifs = this.gifData.filter((i: any) => !existingIds.has(i.id));
    
    if (newGifs.length === 0) {
        this.getDataInStore();
        this.gifData = [];
        this.searchInput = '';
        return;
    }

    // 构造待添加的GIF数组
    const addGif: GifUrl[] = newGifs.map((i: any) => ({
        id: i.id,
        url: i.images.original.url,
        date: new Date()
    }));

    // 合并当前关键词下已有的存储数据,再统一存入localStorage
    const storageKey = this.searchInput.toUpperCase();
    const existingGifsForKey = JSON.parse(localStorage.getItem(storageKey) || '[]');
    const updatedGifs = [...addGif, ...existingGifsForKey];
    localStorage.setItem(storageKey, JSON.stringify(updatedGifs));
  
    this.getDataInStore();
    this.gifData = [];
    this.searchInput = '';
}

说明

  • getExistingGifIds方法遍历localStorage中所有存储的GIF数据,将已存在的ID存入Set集合,利用Set的O(1)查询效率快速判断重复。
  • 修改后的addToStore先过滤掉已存在的GIF,避免重复添加;同时优化了存储逻辑,不再循环调用setItem,而是合并数据后统一存入,减少localStorage操作次数。
  • 如果没有新GIF需要添加,直接更新页面数据并清空输入即可。

内容的提问来源于stack exchange,提问作者Shweta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 01:20:19