zoukankan      html  css  js  c++  java
  • Angular中怎样通过localStorage实现数据持久化-实现存储搜索历史为例

    场景

    Angular介绍、安装Angular Cli、创建Angular项目入门教程:

    https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/105570017

    Angular新建组件以及组件之间的调用:

    https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/105694997

    通过以上搭建起Angular项目。

    然后参照以下实现

    Angular中实现一个简单的toDoList(待办事项)示例代码:

    https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/105818331

    实现简单的搜索功能。

    在HTML5中,新加入了一个localStorage特性,这个特性主要是用来作为本地存储来使用的,解决了cookie存储空间不足的问题(cookie中每条cookie的存储空间为4k),localStorage中一般浏览器支持的是5M大小,这个在不同的浏览器中localStorage会有所不同。

    注:

    博客:
    https://blog.csdn.net/badao_liumang_qizhi
    关注公众号
    霸道的程序猿
    获取编程相关电子书、教程推送与免费下载。

    实现

    首先新建一个service服务,服务中添加查找与添加和删除的公共方法。

    比如这里在app/services目录下创建storage服务

    ng g service services/storage

    为了实现存储功能,在服务中新建set方法

      set(key,value)
      {
          localStorage.setItem(key,JSON.stringify(value));
      }

    为了实现查询功能(记忆/持久化),新建get方法

      get(key)
      {
        //console.log("调用storage中的get方法成功");
        return JSON.parse(localStorage.getItem(key));
      }

    为了实现删除功能,新建remove方法

      remove(key)
      {
          localStorage.removeItem(key);
    
      }

    service中完整示例代码

    import { Injectable } from '@angular/core' ;
    
    @Injectable({
      providedIn: 'root'
    })
    export class StorageService {
    
      constructor() { }
    
      get(key)
      {
        //console.log("调用storage中的get方法成功");
        return JSON.parse(localStorage.getItem(key));
      }
    
      set(key,value)
      {
          localStorage.setItem(key,JSON.stringify(value));
      }
    
      remove(key)
      {
          localStorage.removeItem(key);
    
      }
    }

    在applmodule.ts中引入创建的服务

    import {StorageService} from './services/storage.service';

    并在MgModule里面的providers里面依赖注入服务

    在使用的页面引入服务并注册服务

    这里在search这个组件中调用服务的方法,所以打开search这个组件的ts

    import {StorageService} from '../../services/storage.service';

    并在构造方法中注册服务

    constructor(private storage:StorageService) { }

    注意这里调用的路径,service服务与组件的位置关系如下

    这里注册服务时在构造方法中private storage:StorageService,storage名字自己随意起,后面的StorageService要与上面引入时

    相对应。

    在search这个组件的html中

    <h2>搜索</h2>
    
    <div class="search">
      <input type="text" [(ngModel)]="keyword" />  <button (click)="doSearch()">搜索</button>
    
        <hr>
        
        <ul>
          <li *ngFor="let item of historyList;let key=index;">{{item}}   ------ <button (click)="deleteHistroy(key)">X</button></li>
        </ul>
    
    
    </div>

    ts中对应的方法doSearch在点击后将数据存储并将此搜索历史存入localStorage

      doSearch(){
    
        if(this.historyList.indexOf(this.keyword)==-1){
    
          this.historyList.push(this.keyword);
          this.storage.set('searchlist',this.historyList);
    
        }    
        this.keyword='';    
      }

    在重新刷新页面中为了能实现不清空/数据持久化,在ngOnInit中 获取localStorage中值

      ngOnInit(): void {
        var searchlist:any= this.storage.get('searchlist');
    
        if(searchlist){
          this.historyList=searchlist;        
        }
      }

    在删除按钮对应的方法中

      deleteHistroy(key){
          
          this.historyList.splice(key,1);
          this.storage.set('searchlist',this.historyList);
      }

    ts中完整示例代码

    import { Component, OnInit } from '@angular/core';
    import {StorageService} from '../../services/storage.service';
    
    @Component({
      selector: 'app-search',
      templateUrl: './search.component.html',
      styleUrls: ['./search.component.scss']
    })
    export class SearchComponent implements OnInit {
    
    
      public keyword:string;
      public historyList:any[]= [];
    
      constructor(private storage:StorageService) { }
    
      ngOnInit(): void {
        var searchlist:any=this.storage.get('searchlist');
    
        if(searchlist){
          this.historyList=searchlist;        
        }
      }
    
      doSearch(){
    
        if(this.historyList.indexOf(this.keyword)== -1){
    
          this.historyList.push(this.keyword);
          this.storage.set('searchlist',this.historyList);
    
        }    
        this.keyword='';    
      }
    
      deleteHistroy(key){
          
          this.historyList.splice(key,1);
          this.storage.set('searchlist',this.historyList);
      }
    
    }

    效果

    可以在调试模式下的Application的Storage下的localStorage中查看

  • 相关阅读:
    vue项目-百度地图-初始化展示覆盖范围(默认中心点和半径),点击切换中心点,地图落点(带数字)
    echarts地图下钻(全国到省)下钻一次
    JSON取值(key是中文或者数字)方式详解
    Chrome 80跨域cookie无法携带
    将博客搬至CSDN
    Django模板渲染,运行时如果报错:TemplateDoesNotExist at
    使用allure serve查看报告提示allure-results does not exists的解决方法
    jupyter lab不能自动打开浏览器和默认打开chrome浏览器的解决办法
    Chrome浏览器安装SwitchyOmega_Chromium插件,以及导入Burp Suite证书,抓取https请求包
    vue安装
  • 原文地址:https://www.cnblogs.com/badaoliumangqizhi/p/12797837.html
Copyright © 2011-2022 走看看