
// storage.service.ts
import {Inject, Injectable, PLATFORM_ID} from '@angular/core';
import {isPlatformBrowser} from '@angular/common';

@Injectable({ providedIn: 'root' })
export class LocalStorageService {

  constructor(@Inject(PLATFORM_ID) private platformId: Object) {}

  getItem(key: string): string | null {
    if (isPlatformBrowser(this.platformId)) {
        const data = localStorage.getItem(key);
        try {
          return data ? JSON.parse(data) : null;
        } catch (e) {
          console.error('LocalStorage解析异常:', e);
          return null;
        }
    }
    return null;  // 服务端返回默认值
  }

  setItem<T>(key: string, value: T): void {
    try {
      const data = JSON.stringify(value);
      localStorage.setItem(key, data);
    } catch (e) {
      console.error('LocalStorage存储失败:', e);
    }
  }


  removeItem(key: string): void {
    localStorage.removeItem(key);
  }

  clear(): void {
    localStorage.clear();
  }
}
