数据缓存服务StorageService封装及使用

这篇博客介绍了如何在Angular应用中利用LocalStorage服务进行数据存储、检索和删除操作。通过`StorageService`服务,实现了在组件中获取和设置搜索历史列表,并在页面刷新时从缓存中恢复数据。同时展示了如何在组件中调用服务的方法来添加、删除历史记录,确保数据在客户端的持久化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class StorageService {

  constructor() { }

  get(key:any){
    return JSON.parse(localStorage.getItem(key)||'0')
  }
  set(key:any,value:any){
    localStorage.setItem(key,JSON.stringify(value));
  }
  remove(key:any){
    localStorage.removeItem(key)
  }
}

使用方法:
search.components.ts中,数据缓存到searchlist中。使用生命周期函数,检查每次刷新页面时,如果searchlist存在则从缓存中拿取数据,删除也是。

import { Component, OnInit } from '@angular/core';
//引入服务
import { StorageService } from 'src/app/services/storage.service';
//实例化服务
// var storage = new StorageService();

@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.less']
})
export class SearchComponent implements OnInit {

  constructor(public storage:StorageService) {
    //使用服务
    // storage.get();
    // this.storage.get(key);
   }
  public content:string='';
  public historyList:any[] = []; 
  ngOnInit(): void {
    //生命周期函数,如果searchlist存在则从缓存中拿取数据
    var searchlist = this.storage.get('searchlist');
    if(searchlist){
      this.historyList=searchlist;
    }
  }
  //列表中添加历史记录
  doSearch(){
    if(this.historyList.indexOf(this.content)==-1){
      this.historyList.push(this.content);
      this.storage.set('searchlist',this.historyList);

    }
    this.content = '';
    console.log(this.historyList);
  }
  //删除指定记录
  deleteHistory(key:any){
    alert(key);
    this.historyList.splice(key,1);
    this.storage.set('searchlist',this.historyList);
  }
  

}

可以在检查–Application–localStorage中查看到searchlist
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值