Angular中从本地存储读写用户设置的框架
创始人
2024-10-31 01:00:54
0
  1. 创建一个名为 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();
  }

}
  1. 在组件中使用 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 在本地存储中读写用户设置了。

相关内容

热门资讯

透视私人房!模拟器打开hhpo... 透视私人房!模拟器打开hhpoker(透视)开挂辅助app(确实是真的挂)-哔哩哔哩1、该软件可以轻...
七分钟教材!心悦填大坑辅助器免... 七分钟教材!心悦填大坑辅助器免费下载,有没有人会衢州都莱的辅助,黑科技教程(有挂方针)-哔哩哔哩1、...
透视黑科技!大菠萝免费辅助,w... 透视黑科技!大菠萝免费辅助,wepoker破解工具,项目教程(好像真的有挂)-哔哩哔哩1)大菠萝免费...
透视专用!wepoker私人局... 透视专用!wepoker私人局辅助器怎么用(透视)开挂辅助工具(确实存在有挂)-哔哩哔哩1、wepo...
透视有挂!wepoker透视脚... 透视有挂!wepoker透视脚本苹果版,竞技联盟透视插件,教材教程(都是真的有挂)-哔哩哔哩1、不需...
三分钟法门!越乡有辅助软件,四... 三分钟法门!越乡有辅助软件,四川途游辅助软件下载,揭秘教程(有挂技巧)-哔哩哔哩1、起透看视 四川途...
透视黑科技!线上德州的辅助器是... 透视黑科技!线上德州的辅助器是什么(透视)开挂辅助攻略(切实真的有挂)-哔哩哔哩1、玩家可以在线上德...
透视能赢!pokernow辅助... 透视能赢!pokernow辅助控制,wepoker有没有辅助,阶段教程(本来真的有挂)-哔哩哔哩1、...
九分钟窍门!乐玩游戏辅助工具,... 九分钟窍门!乐玩游戏辅助工具,新芒果监利开机贴吧,黑科技教程(有挂方法)-哔哩哔哩小薇(透视辅助)致...
透视线上!wepoker有没有... 透视线上!wepoker有没有透视方法(透视)开挂辅助方法(原来有挂)-哔哩哔哩1、进入游戏-大厅左...