创建服务命令 ng g service services/storage
在我们的services目录下创建了stroage.service.ts文件,class初始了类StorageService
所以在app.module.ts 里面引入创建的服务时,名字最好一致
import { StorageService } from './services/storage.service';
服务放在数组 providers: [StorageService], /*定义的服务 回头放在这个里面*/
storage.service.ts 封装存储localstroage
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class StorageService {
constructor() { }
set(key, value) {
localStorage.setItem(key, JSON.stringify(value))
}
get(key) {
return JSON.parse(localStorage.getItem(key))
}
remove(key) {
localStorage.removeItem(key)
}
}
todolist.component.ts
import { Component, OnInit } from '@angular/core';
import { StorageService } from '../../services/storage.service' //引入服务
@Component({
selector: 'app-todolist',
templateUrl: './todolist.component.html',
styleUrls: ['./todolist.component.css']
})
export class TodolistComponent implements OnInit {
// public storage = new StorageService() // 可以引入和使用服务,官方不推荐这样
public username: any
public list = []
// private storage:StorageService 依赖注入服务
constructor(private storage: StorageService) {
this.username = ''
// console.log(this.storage)
// this.storage.set('username', 'angular')
// alert(this.storage.get('username'))
}
ngOnInit() {
//每次刷新获取storage里面 todolist的值
var todolist = this.storage.get('todolist');
if (todolist) {
this.list = todolist;
}
}
add(e) {
// alert(this.username) 数据双向绑定可以获取到文本框的值
// console.log(e)
//1.从storage获取 todolist的数据
//2.如果有数据,拿到这个数据,然后把新数据和这个storage数据拼接,重新写入
//3.如果没有数据 直接给storage写入数据
if (e.keyCode == 13 || e.type == 'click') {
let obj = { // 每次增加的对象数据
username: this.username,
status: 1
}
console.log(e.target.value)
let todolist = this.storage.get('todolist');
if (todolist) {
todolist.push(obj);
//如果有数据,拿到这个数据,然后把新数据和这个storage数据拼接,重新写入
this.storage.set('todolist', todolist);
} else {
//3.如果没有数据 直接给storage写入数据
var arr = [];
arr.push(obj);
this.storage.set('todolist', arr);
}
this.list.push(obj)
}
}
delete(key) {
this.list.splice(key, 1)
}
changeData(key,status) {
this.list[key].status = status
this.storage.set('todolist', this.list)
}
}