angular是基于一个组件化,模块化的开发方式。组件里面他是一个相互隔离的,不同组件之间之间的方法是不能相互调用的,如果要在组件里面调用公共的方法的话我们就把这个方法放到一个叫做服务的地方。之后想在那个组件用服务的方法,我们就把服务引入,引入之后就可以在对应的组件里面使用公共的方法。
创建并且使用服务
//1.首先我们创建一个服务,cli给我们提供了指令 我们这里就直接用指令来创建
服务| ng g service my-new-service
//2.创建完成之后需要我们在app.module.ts里面引入,并且配置服务
// 引入服务
import {StorageService} from './services/storage.service'
// 配置服务
providers: [StorageService]
//3.接下来你想在哪个组件里面使用服务,就在哪个组件里面导入
//在组件中引入
import {StorageService} from '../../services/storage.service'
//使用服务
constructor(public storage:StorageService) {
console.log(this.storage.get());
}
持久化数据
在storage.servie.ts中我们做数据持久化处理:
export class StorageService {
constructor() { }
// 浏览器不解读数组,它只存字符串,所以你需要转JSON,JSON是字符串
// 在缓存的时候,只要你这个数据不是字符串 是其他复杂类型的都需要做一个序列化存成json格式
set(key:string,value:any){
// localStorage.setItem(key,value)
localStorage.setItem(key,JSON.stringify(value))
}
// 取数据的时候再做一个反序列化转回来
get(key: any) {
// return JSON.parse(key)
let getValue:any = localStorage.getItem(key)
return JSON.parse(getValue);//反序列化
}
remove(key){
return localStorage.removeItem(key)
}
}
之后我们在search.component.ts里面使用
export class SearchComponent implements OnInit {
public keywords:string = ''
public historyList:any[] = []
//1.先作声明
constructor(public storage:StorageService) {
}
ngOnInit() {
// 每次组件刷新都会加载这个生命周期函数
console.log('每次组件刷新都会加载这个生命周期函数');
//3.每次组件加载的时候从缓存中来取数据
var searchList:any = this.storage.get('searchResult')
console.log('searchList',searchList);
if(searchList){
//4.读缓存
this.historyList = searchList
}
}
doSearch(){
console.log(this.keywords, 'this.keywords');
if(this.historyList.indexOf(this.keywords)=== -1){
this.historyList.push(this.keywords)
console.log(this.historyList);
//2.做缓存
this.storage.set('searchResult',this.historyList)
this.keywords = ''
}
}
doDel(key){
this.historyList.splice(key,1)
//做缓存
this.storage.set('searchResult',this.historyList)
}
}
这样的话就实现了数据的缓存