ts封装localStorage和sessionStorage
时间: 2024-08-16 13:07:46 浏览: 59
在TypeScript中,为了更好地管理和封装浏览器的localStorage和 sessionStorage,我们可以创建自定义的模块或类来处理数据存储。以下是基本的步骤:
1. 定义一个`LocalStorageService`或`SessionStorageService`类:
```typescript
import { Storage } from 'ionic-framework/dist/util';
class LocalStorageService {
private storage: Storage = window.localStorage;
// 获取存储的数据
public get(key: string): any {
return this.storage.getItem(key);
}
// 存储数据
public set(key: string, value: any) {
this.storage.setItem(key, JSON.stringify(value));
}
// 删除数据
public remove(key: string) {
this.storage.removeItem(key);
}
// 清空所有数据
public clear() {
this.storage.clear();
}
}
// 对于sessionStorage,可以类似地创建一个SessionStorageService类
class SessionStorageService {
private storage: Storage = window.sessionStorage;
// ... (同上,替换localStorage为sessionStorage)
}
```
2. 使用服务:
```typescript
constructor(private localStorageSvc: LocalStorageService) {}
// 示例
public saveData(key: string, data: any) {
this.localStorageSvc.set(key, data);
}
public getData(key: string): any {
return this.localStorageSvc.get(key);
}
```
阅读全文