// General syntax for storing data
localStorage.setItem('key', 'value');
// Also note that both the key & the value has to be strings.
// So we stringify the value(if it's an object) before setting it.
// So, if you have an object that you want to save, stringify it like this
let data = {
'token': 'token',
'name': 'name'
};
localStorage.setItem('myLSkey', JSON.stringify(data));
// OR for individual key-value pairs
localStorage.setItem('myLSkey', JSON.stringify({
'token': 'token',
'name': 'name'
}));
// To retrieve the data & save it to an existing variable
data = JSON.parse(localStorage.getItem('myLSkey'));
// To remove a value/item from localStorage
localStorage.removeItem("myLSkey");
Tips : < br > You 也可以使用一个软件包为您的角度应用程序,这是基于
本地 localStorage API (我们在上面使用的)来实现这一点
您不必担心 stringify 和 parse,看看这个
角度5及以上的包装。 @ ngx-pwa/local-Storage < br > < br >
你也可以在谷歌上快速搜索“ maybe”,< strong > angle local
Storage ,& find a package that has even more Github stars 等等
//set the data
localStorage.setItem(key, value); //syntax example
localStorage.setItem('tokenKey', response.json().token);
//get the data
localStorage.getItem('tokenKey')
//confirm if token is exist or not
return localStorage.getItem('tokenKey') != null;
localStorage.setItem("name","Muthu");
if(localStorage){ //it checks browser support local storage or not
let Name=localStorage.getItem("name");
if(Name!=null){ // it checks values here or not to the variable
//do some stuff here...
}
}
sessionStorage.setItem("name","Muthu");
if(sessionStorage){ //it checks browser support session storage/not
let Name=sessionStorage.getItem("name");
if(Name!=null){ // it checks values here or not to the variable
//do some stuff here...
}
}
您也可以考虑使用我维护的库: < a href = “ https://github.com/zoomSphere/ngx-store”rel = “ norefrer”> ngx-store (npm i ngx-store)
它使得使用 localStorage、 sessionStorage 和 cookies 变得非常简单:
1) 设计师:
export class SomeComponent {
@LocalStorage() items: Array<string> = [];
addItem(item: string) {
this.items.push(item);
console.log('current items:', this.items);
// and that's all: parsing and saving is made by the lib in the background
}
}
export class SomeComponent {
constructor(localStorageService: LocalStorageService) {}
public saveSettings(settings: SettingsInterface) {
this.localStorageService.set('settings', settings);
}
public clearStorage() {
this.localStorageService.utility
.forEach((value, key) => console.log('clearing ', key));
this.localStorageService.clear();
}
}
3) 构建器模式:
interface ModuleSettings {
viewType?: string;
notificationsCount: number;
displayName: string;
}
class ModuleService {
constructor(public localStorageService: LocalStorageService) {}
public get settings(): NgxResource<ModuleSettings> {
return this.localStorageService
.load(`userSettings`)
.setPath(`modules`)
.setDefaultValue({}) // we have to set {} as default value, because numeric `moduleId` would create an array
.appendPath(this.moduleId)
.setDefaultValue({});
}
public saveModuleSettings(settings: ModuleSettings) {
this.settings.save(settings);
}
public updateModuleSettings(settings: Partial<ModuleSettings>) {
this.settings.update(settings);
}
}
另一个重要的事情是您可以监听(每一个)存储更改,例如(下面的代码使用 RxJS v5语法) :
this.localStorageService.observe()
.filter(event => !event.isInternal)
.subscribe((event) => {
// events here are equal like would be in:
// window.addEventListener('storage', (event) => {});
// excluding sessionStorage events
// and event.type will be set to 'localStorage' (instead of 'storage')
});