添加本地缓存功能

301 阅读1分钟

添加本地缓存功能

xxx.service

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

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

  constructor() { }

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


//   记得在 app.module.ts 引入

html

<h3>添加了本地缓存的功能.localStorage....service</h3>
<input type="text" [(ngModel)]="keywords"  (keyup)='doAdd($event)' />
<button (click)="doSearch()">search....</button>

<hr>

<h3>待办事项</h3>
<ul>
  <li *ngFor="let item of history_List;  let key=index;"  [hidden]="item.status == 1" >
      <input type="checkbox" [(ngModel)]="item.status" [id]="'checkbox' + key" /> <label [for]="'checkbox' + key" >{{item.title}}</label>   --- <button (click)="delete_history(key)">X</button>
</li>
</ul>

<hr>

<h3>已经完成的事</h3>
<ul>
    <li *ngFor="let item of history_List;  let key=index;"  [hidden]="item.status == 0" >
      <input type="checkbox" [(ngModel)]="item.status"  [id]="'checkbox' + key"  />  <label  [for]="'checkbox' + key"  > {{item.title}}</label>  ---- <button (click)="delete_history(key)">X</button>
  </li>
  </ul>

component.ts

import { Component, OnInit } from '@angular/core';
import { XxxxxService } from '../xxxxx.service';



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

  public keywords:string;
  public history_List:any[] = [
    {
      title:'do homeword',
      status:0
    },
    {
      title:'go shopping',
      status:1
    },
    {
      title:'play games',
      status:0
    },

  ];

  constructor(public xxxxx:XxxxxService) { }

  ngOnInit() {
    let searchlist = this.xxxxx.get('search_histroy');
    if(searchlist){
      this.history_List = searchlist;
    }
  }

  doSearch(){
    //   如果关键字不存在 返回-1  就push  也就是有没有重复的数据
    if(this.if_has_ketwords(this.history_List , this.keywords)){
        this.history_List.push({
          title:this.keywords,
          status:0         // 0 表示 待办事项  1 表示已经完成的事项
        });
        this.xxxxx.set('search_histroy' , this.history_List);
        
    }
    this.keywords='';
  }

  doAdd(ev){
    if(ev.keyCode == 13){
      this.doSearch();
    }
  }

  delete_history(key){
    this.history_List.splice(key,1);
  }



  if_has_ketwords(history_List:any , keywords:any){

    if(!keywords){
      return false;
    }

    for(let i=0 ; i < history_List.length;i++){
      if(history_List[i].title == keywords){
        return false;
      }
    }

    return true;

  }

}


app.module.ts

import { FormsModule } from '@angular/forms';

  imports: [
    BrowserModule,
    FormsModule
  ],