1、创建ts文件
export class LocalStorage {
public localStorage:any;
constructor() {
if (!localStorage) {
throw new Error('Current browser does not support Local Storage');
}
this.localStorage = localStorage;
}
public set(key:string, value:string):void {
this.localStorage[key] = value;
}
public get(key:string):string {
return this.localStorage[key] || false;
}
public setArr(key:string, value:Array<any>):void{
this.localStorage[key] = value;
}
public setObject(key:string, value:any):void {
this.localStorage[key] = JSON.stringify(value);
}
public getObject(key:string):any {
return JSON.parse(this.localStorage[key] || '{}');
}
public remove(key:string):any {
this.localStorage.removeItem(key);
}
public removeAll():any{
this.localStorage.clear();
}
}
2、在app.module.ts中引用
@NgModule({
providers: [LocalStorage,...],
})
3、在组件(component)中使用
import {LocalStorage} from "...";
constructor(
private local: LocalStorage,
)
setMessage(name,psd){
const json = {userName:name,pass:psd};
this.local.setObject('msg',json);
}
getMessage(){
const userMsg=this.local.getObject('msg');
}