service即一堆component的集合
1. 创建服务命令
创建到指定目录下面
ng g service services/storage
2.app.module.ts 里面引入创建的服务
import { StorageService } from './services/storage.service';
NgModule 里面的 providers 里面依赖注入服务
providers: [StorageService],
3.使用的页面引入服务,注册服务
```javascript
import { StorageService } from '../../services/storage.service';
constructor(private storage: StorageService) {}
<pre class="line-numbers prism-highlight" data-start="1"><code class="language-null"># 4.ts里面加入缓存逻辑
```javascript
export class TodolistComponent implements OnInit {
list=[];
thing="";
constructor(private storage:StorageService) { }
ngOnInit() {
if(this.storage.get('tdlist')){
this.list = this.storage.get('tdlist');
}
}
add(){
var obj={"name":this.thing,"status":0};
this.list.push(obj);
this.thing="";
this.storage.set('tdlist',this.list);
}
del(key){
this.list.splice(key,1);
this.storage.set('tdlist',this.list);
}
change(key,status){
this.list[key].status=status;
this.storage.set('tdlist',this.list);
}
}
```
# 5 实现storage服务
```javascript
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);
}
}