1、创建服务
ng g service 服务名
ng g service 文件名/服务名
2、在app.module.ts中引入并声明服务
import { StorageService } from './services/storage.service'
@NgModule({
providers: [StorageService], // 配置项目所需要的服务
})
3、在服务中定义公共方法
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class StorageService {
constructor() { }
// 定义方法
set() {
// 存储
window.localStorage.setItem('变量名', JSON.stringify(变量值));
}
get() {
// 获取
window.localStorage.getItem('变量名');
}
remove() {
// 删除
window.localStorage.removeItem('变量名');
}
}
4、在组件中引入服务并使用方法
import { StorageService } from '../../services/storage.service'
constructor(public storage: StorageService) {
this.storage.set(); // 调用服务中的设置本地缓存数据的方法
this.storage.get(); // 调用服务中的获取本地缓存数据的方法
this.storage.remove(); // 调用服务中的删除本地缓存数据的方法
}