localStorage和sessionStorage是web storage的的两种存储方式,存储客户端临时信息的对象。
localStorage前者用于持久化的本地存储,除非主动删除数据,否则数据是永远不会过期的。
sessionStorage存储的数据只有在同一个会话中的页面才能访问并且当会话结束后数据也随之销毁。因此sessionStorage不是一种持久化的本地存储,仅仅是会话级别的存储。
这里可以设计一个SessionStorage类封装一下SessionStorage的API,提供增删改查操作,用户在登录成功后做一些Promise请求,获取一些诸如项目信息,用户信息,权限信息以及所需字典信息等等添加到SessionStorage中。
SessionStorage.ts
export class SessionStorage{
public SetItem(key:string,option :any){
try{
const data:string = JSON.Stringfy(option);
} catch(err){
Promise.reject(err);
}
}
public GetItem(key:string){
try{
const data:string | null = window.sessionStorage.getItem(key);
if(data === null){
return data;
}
return JSON.Stringfy(data);
} catch(err){
Promise.reject(err);
}
}
public RemoveItem(key:string){
try{
window.sessionStorage.removeItem(key);
} catch(err){
Promise.reject(err);
}
}
public clear(){
try{
window.sessionStorage.clear();
} catch(err){
Promise.reject(err);
}
}
}
export const session = new SessionStorage();
外面方法需要操作SessionStorage时引入session就可以使用了。
业务操作时
const value = sessionStorage.getItem('key');
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。