使用angular服务、本地存储实现todolist
服务的创建与使用:
创建服务
ng g s services/storage
服务的配置:在app.module.ts中引入并声明
import { StorageService } from './services/storage.service';
providers: [StorageService]
使用:在使用的组件的ts中引入并使用
import { StorageService } from 'src/app/services/storage.service';
constructor(public storage: StorageService) { // 获取服务的实例
let serverGet = storage.get();
console.log(serverGet)
}
html:
<div class="container">
<input type="text" [(ngModel)]="keyword" (keyup)="doAdd($event)">
<hr>
<h3>待办事项:</h3>
<ul>
<li *ngFor="let item of todolist; let key = index;" [hidden]="item.status == 1">
<input type="checkbox" [(ngModel)]="item.status" (change)="checkBoxChange()" />
{{item.title}} -----------
<button (click)="deleteData(key)">删除</button>
</li>
</ul>
<h3>已完成事项:</h3>
<li *ngFor="let item of todolist; let key = index;" [hidden]="item.status == 0">
<input type="checkbox" [(ngModel)]="item.status" (change)="checkBoxChange()" />
{{item.title}} -----------
<button (click)="deleteData(key)">删除</button>
</li>
</div>
ts:
import { Component, OnInit } from '@angular/core';
import { StorageService } from 'src/app/services/storage.service';
@Component({
selector: 'app-todolist',
templateUrl: './todolist.component.html',
styleUrls: ['./todolist.component.styl']
})
export class TodolistComponent implements OnInit {
public keyword: string;
public todolist: any[] = [];
constructor(public storage: StorageService) {
}
ngOnInit() {
let todolist: any = this.storage.get("todolist");
if(todolist) {
this.todolist = todolist;
}
}
doAdd(e) {
if (e.keyCode == 13) {
if(!this.todolistHasKeyword(this.todolist, this.keyword)) {
this.todolist.push({
title: this.keyword,
status: 0 // 0表示待办事项,1表示已完成事项
});
this.keyword = '';
this.storage.set("todolist", this.todolist);
}else {
alert("数据已存在!");
}
}
}
checkBoxChange() {
console.log('tag', '')
}
deleteData(index) {
this.todolist.splice(index, 1);
this.storage.set("todolist", this.todolist);
}
todolistHasKeyword(todolist: any, keyword: any) {
// 异步会存在问题
// todolist.forEach(value => {
// if(value.title == keyword) {
// return true;
// }
// });
if(!keyword) return false;
for(var i = 0 ; i < todolist.length ; i++) {
if(todolist[i].title == keyword) {
return true;
}
}
return false;
}
}
services:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class StorageService {
constructor() { }
set(key: string, value: any) {
localStorage.setItem(key, JSON.stringify(value));
}
get(key: string) {
return JSON.parse(localStorage.getItem(key));
}
remove(key: string) {
localStorage.removeItem(key);
}
}
效果: