继续上一篇【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/>
搜索 <input type="text" name="search" id="search" (keydown)="keyDownAddSearch($event)" [(ngModel)]="searchItem" />
<button (click)="addSearch()">🔍</button>
</li>
<li>
<br/>
<strong> 【待办事项】:</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>
<button title="删除" [ngClass]="{'btn': true}" (click)="deleteHistryItem(key)">X</button><br/>
</section>
</span>
</li>
</ol>
</li>
<li>
<br/>
<strong> 【已办事项】:</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>
<button title="删除" [ngClass]="{'btn': true}" (click)="deleteHistryItem(key)">X</button><br/>
</section>
</span>
</li>
</ol>
</li>
<li>
<br/>
<strong [ngStyle]="{'color': 'red'}"> {{titleMsg}} </strong>
</li>
</ul>
</section>
最后【ToDoList 功能】完成,当浏览器页面刷新时,数据被存储到浏览器BOM对象【Local Storage】,实现浏览器环境本地存储。