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 在本地存储中读写用户设置了。

相关内容

热门资讯

玩家必用!爱玩辅助有挂吗软件(... 玩家必用!爱玩辅助有挂吗软件(辅助挂)wpk私人辅助(一直真的是有挂);1、很好的爱玩辅助有挂吗软件...
总算了解!蜀山四川小程序破解版... 您好,蜀山四川小程序破解版下载这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很...
一分钟带你了解!皮皮跑子辅助(... 一分钟带你了解!皮皮跑子辅助(辅助挂)wepoker私人局俱乐部(原生有挂);致您一封信;亲爱皮皮跑...
终于清楚!河南微乐麻将小程序辅... 终于清楚!河南微乐麻将小程序辅助器(辅助挂)德普辅助app(其实存在有挂);相信小伙伴都知道这个河南...
技巧知识分享!创思维激k辅助神... 技巧知识分享!创思维激k辅助神器(辅助挂)hhpoker作弊码(果然有挂);1、超多福利:超高返利,...
玩家必看科普!宝宝浙江游戏作弊... 玩家必看科普!宝宝浙江游戏作弊是真的假的(辅助挂)佛手大菠萝有挂吗(果然是真的有挂);宝宝浙江游戏作...
程序员教你!广东闲来app辅助... 程序员教你!广东闲来app辅助(辅助挂)wpk免费辅助(果然是真的有挂)是一款可以让一直输的玩家,快...
玩家必知教程!小逸碰胡插件脚本... 玩家必知教程!小逸碰胡插件脚本(辅助挂)hhpoker买挂(从来存在有挂);小逸碰胡插件脚本AI智能...
记者发布!微信小程序游戏破解微... 记者发布!微信小程序游戏破解微乐游戏(辅助挂)拱趴大菠萝挂哪里(原生存在有挂);1、玩家可以在微信小...
9分钟了解!微乐小程序辅助工具... 9分钟了解!微乐小程序辅助工具(辅助挂)大菠萝辅助器(确实真的有挂);大家肯定在之前微乐小程序辅助工...