Angular 服务(service)实现 ToDoList 数据持久化

继续上一篇【ToDoList 功能】完善,通过ng服务和BOM对象【Local Storage】实现数据的持久化。

首先通过 Angular CLI 命令【ng generate service services/dataStorange】创建一个服务【dataStorange】,代码示例如下:

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

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

  public serviceData:string = '我是服务中的数据';
  constructor() { }

  //获取数据
  get(key:string):any {
    return JSON.parse(localStorage.getItem(key)); //localStorage 是浏览器(BOM)对象
  }

  //保存数据
  set(key:string, value:any):void{
    localStorage.setItem(key,JSON.stringify(value));
  }

  //删除数据
  remove(key:string):void{
    localStorage.removeItem(key);
  }

}

然后继续改造【JdAppToDoList】组件:【jd-app-to-do-list.component.ts】

import { Component,OnInit } from '@angular/core';

//引入服务 DataStorageService
import { DataStorageService } from '../../services/data-storage.service';

@Component({
  selector: 'app-jd-app-to-do-list',
  templateUrl: './jd-app-to-do-list.component.html',
  styleUrls: ['./jd-app-to-do-list.component.css']
})
export class JdAppToDoListComponent implements OnInit {

  private readonly dataKey:string = 'todoList'; //存储数据对象的键,获取数据时使用
  public searchItem:string = ''; //搜索关键字
  public todoList:Array =[]; //保存搜索历史
  public titleMsg:string = ''; //提示信息

  //构造函数DI(依赖注入)注册服务【DataStorageService】
  constructor(public dataStorage:DataStorageService) {
    let data:any = this.dataStorage.get(this.dataKey);
    if (data != null) {
      this.todoList = data;
    }
  }

  ngOnInit():void {

  }

  //敲回车【Enter】键执行添加搜索项
  keyDownAddSearch(e:any): void {
    if (e.keyCode == 13) {
      this.addSearch();
    }
  }

  //添加搜索记录
  addSearch():void {
    this.titleMsg = '';
    if (this.searchItem !='') {
      let isHas: boolean = this.checkHasItem(this.todoList, this.searchItem);
      if (!isHas) {
        let item: object = {
          title: this.searchItem,
          time: new Date(),
          checked: false
        };
        this.todoList.push(item);
        this.dataStorage.set(this.dataKey,this.todoList); //保存服务,数据持久化
      } else {
        this.titleMsg = '提示:历史中已经存在!';
      }
      this.showHistrySearch();
    }else{
      this.titleMsg = '提示:请输入要查找的信息!';
    }
  }

  //检查列表中是否存在重复项目
  checkHasItem(list:any, seachVal:string):boolean {
    for (let i = 0; i < list.length; i++) {
      const item = list[i];
      if (item.title==seachVal) {
        return true;
      }
    }
    return false;
  }

  //显示搜索历史信息
  showHistrySearch(): void{
    console.log(this.todoList);
  }

  //删除历史记录项
  deleteHistryItem(i:string):void {
    let items:object[] = this.todoList.splice(parseInt(i),1);
    this.dataStorage.set(this.dataKey,this.todoList); //保存服务,数据持久化
    console.log('被删除的项目:'+ items);
  }
 
  //监听多选框改变时重新存储数据
  changeCheckbox():void{
    console.log('sdfds');
    let tmpData:Array = this.dataStorage.get(this.dataKey);
    if (tmpData!=this.todoList) {
      this.dataStorage.remove(this.dataKey);
      this.dataStorage.set(this.dataKey,this.todoList); //保存服务,数据持久化
    }
  }

}
 
  

组件页面添加多选框【checkbox】选择状态改变时对数据存储的监听,添加方法 【(change)="changeCheckbox()"】:

  • ToDoList

  •  搜索  

  •  【待办事项】:

    1. { {item.time | date:'yyyy/MM/dd & hh-mm-ss'}}  

  •  【已办事项】:

    1. { {item.time | date:'yyyy-MM-dd / HH-mm-ss'}}  

  •   { {titleMsg}}

最后【ToDoList 功能】完成,当浏览器页面刷新时,数据被存储到浏览器BOM对象【Local Storage】,实现浏览器环境本地存储。

你可能感兴趣的:(Angular,service)