Last active
June 19, 2017 09:51
-
-
Save rhyttr/e53777fe60f60eac7cffb04cf4ab5d14 to your computer and use it in GitHub Desktop.
angular local storage
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
http://www.jianshu.com/p/94afa6c4dbc1 | |
#实现: | |
添加文件app/core/common/local.storage.ts(文件位置根据自己喜好) | |
import {Provider} from '@angular/core'; | |
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 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); | |
} | |
} | |
// export const LOCAL_STORAGE_PROVIDERS:any[] = [ | |
// Provider(LocalStorage, {useClass: LocalStorage}) | |
// ]; | |
# 使用: | |
## 在文件app.module.ts 中引用 | |
import { LocalStorage } from './core/common/local.storage'; | |
... | |
@NgModule({ | |
... | |
providers: [LocalStorage,...], | |
... | |
}) | |
## 在你的Component 中使用 | |
... | |
// 引用 | |
import { LocalStorage } from '../core/common/local.storage' | |
// 注入 | |
constructor( | |
private ls: LocalStorage, | |
... | |
) | |
get(): void { | |
// 读取LocalStorage | |
this.cache = this.ls.getObject("logincache") ; | |
} | |
set(): void { | |
// 写入LocalStorage | |
this.ls.setObject("logincache",this.cache) ; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment