LocalStorageService
的服务:import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class LocalStorageService {
constructor() { }
public setItem(key: string, value: any): void {
localStorage.setItem(key, JSON.stringify(value));
}
public getItem(key: string): any {
const item = localStorage.getItem(key);
return item ? JSON.parse(item) : null;
}
public removeItem(key: string): void {
localStorage.removeItem(key);
}
public clear(): void {
localStorage.clear();
}
}
LocalStorageService
例如,我们要在组件中存储一个布尔值:
import { Component } from '@angular/core';
import { LocalStorageService } from './local-storage.service';
@Component({
selector: 'app-my-component',
template: `
Setting value: {{ settingValue }}
`
})
export class MyComponent {
settingKey = 'my-setting';
settingValue = false;
constructor(private localStorageService: LocalStorageService) {
const storedValue = this.localStorageService.getItem(this.settingKey);
if (storedValue !== null) {
this.settingValue = storedValue;
}
}
toggleSetting(): void {
this.settingValue = !this.settingValue;
this.localStorageService.setItem(this.settingKey, this.settingValue);
}
}
这样就可以使用 LocalStorageService
在本地存储中读写用户设置了。