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<object> =[]; //保存搜索历史
  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<object> = this.dataStorage.get(this.dataKey);
    if (tmpData!=this.todoList) {
      this.dataStorage.remove(this.dataKey);
      this.dataStorage.set(this.dataKey,this.todoList); //保存服务,数据持久化
    }
  }

}

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

<section id="bgSection">
    <ul id="ul">
        <li [ngStyle]="{'background-color': '#333','color':'#999'}">ToDoList</li>
        <li>
            <br/>
            &nbsp;搜索 <input type="text" name="search" id="search" (keydown)="keyDownAddSearch($event)" [(ngModel)]="searchItem" />&nbsp;
            <button (click)="addSearch()">🔍</button>
        </li>
        <li>
            <br/>
            <strong>&nbsp;【待办事项】:</strong>
            <ol>
                <li>
                    <span *ngFor="let item of todoList; let key=index" >
                        <section *ngIf="!item.checked" [ngStyle]="{'color': 'red','border':'1px solid orange'}">
                            <input type="checkbox" [value]="item.title" [name]="item.title" [id]="'item'+key" (change)="changeCheckbox()"  [(ngModel)]="item.checked" /> 
                            <label [for]="'item'+key"> {{item.title}} </label> <br/>
                            <span>{{item.time | date:'yyyy/MM/dd & hh-mm-ss'}}</span> &nbsp;
                            <button title="删除" [ngClass]="{'btn': true}" (click)="deleteHistryItem(key)">X</button><br/>
                        </section>
                    </span>
                </li>
            </ol>
        </li>
        <li>
            <br/>
            <strong>&nbsp;【已办事项】:</strong>
            <ol>
                <li>
                    <span *ngFor="let item of todoList; let key=index">
                        <section *ngIf="item.checked"  [ngStyle]="{'color': 'green','border':'1px solid orange'}">
                            <input type="checkbox" [value]="item.title" [name]="item.title" [id]="'item'+key" (change)="changeCheckbox()" [(ngModel)]="item.checked" /> 
                            <label [for]="'item'+key"> {{item.title}} </label> <br/>
                            <span>{{item.time | date:'yyyy-MM-dd / HH-mm-ss'}}</span> &nbsp;
                            <button title="删除" [ngClass]="{'btn': true}" (click)="deleteHistryItem(key)">X</button><br/>
                        </section>
                    </span>
                </li>
            </ol>
        </li>
        <li>
            <br/>
            <strong [ngStyle]="{'color': 'red'}">&nbsp; {{titleMsg}} </strong>
        </li>
    </ul>
</section>

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ChaITSimpleLove

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值