import { Injectable, Self, Inject, InjectionToken } from '@angular/core'; export function _localStorage() { return localStorage; } export const BROWSER_LOCALSTORAGE = new InjectionToken('Browser LocalStorage', { providedIn: 'root', factory: _localStorage }); /** * localStorage生命周期是永久 * 只能存储字符串类型的对象 * * @export */ @Injectable() export class NaLocalStorageService { constructor(@Inject(BROWSER_LOCALSTORAGE) public storage: any) { } public set(key: string, value: string): void { this.storage.setItem(key, value); } public get(key: string): string { return this.storage.getItem(key); } public setObject(key: string, value: any): void { // 将value转变为字符串存储 this.storage.setItem(key, ((value == null) ? null : JSON.stringify(value))); } public getObject(key: string): any { return JSON.parse(this.storage.getItem(key)); } public remove(key: string): any { this.storage.removeItem(key); } }