角存储
饼干、会话和本地版的装饰和服务
这个图书馆添加了装饰器 使得它非常容易 自动 使用 HTML5 保存并恢复变量 localStorage 财务报告和审定财务报表 sessionStorage。它也提供Angular-Injectable session-和本地服务.
包含什么?
- 相当容易使用和配置的装饰函数(参见 装饰器配置:
@LocalStorage()- 在 HTML5 本地服务器中保存变量@SessionStorage()- 在 HTML5 会话中保存变量Storage@CookieStorage()- 将变量保存为饼干@SharedStorage()- 将可跨类共享的变量保留在临时记忆中@TempStorage()- 别名用于SharedStorage
- 可注射
LocalStorageService, (中文(简体) ),SessionStorageService, (中文(简体) ),CookiesStorageService财务报告和审定财务报表SharedStorageService(单位:千美元)这里读更多(中文(简体) ) - 可能性 监听存储更改
- 简单配置( 见 # 配置 # 页:1
- 测试覆盖率
变化
v3.0.0 - 支持角 9
缩放层的版本
v2.1.0 - 支持 Angular 7 & TypeScript 3
v2.0.0 - 支持角6 (RxJS v6)
v 1.4.x
- 标准化行为:
- 超过1个装饰器,例如:
@LocalStorage() @CookieStorage() variable: any;CookieStorage(更接近变量的装饰)具有更高的优先级,因此该值将只从cookie读取. 饼干值将被保存到localStorage无论内容如何 都保持一致性. WebStorageService.clear('all')- 现在除去所有东西外ngx-store配置( 存储于localStorage(中文(简体) )
- 超过1个装饰器,例如:
- 删除已折旧( 自 v0. 5 起)
WEBSTORAGE_CONFIG @SharedStorage现在有别名@TempStorage- 介绍 构建器模式
- 增加单位测试覆盖率
- 存储事件的修改
即将来临( TODO)
- 从外部取出密钥的存储事件
- 存储事件测试(接受PR)
- 接受作为终止日期的时机(接受公关)
- 管理 cookie 的更多选项
- 支持设置和地图
- 保存数据的编码
- 从配置 npm 配置'文件 (?) (中文(简体) )
- 自动处理所有使用的数据操作 代理服务器 (ES6) (中文(简体) )
安装
- 下载库 :
npm i @efaps/ngx-store --save或者说npm i ngx-store@RC用于最新版本 - 导入您的 WebStorage 模块
app.module.ts数字 :import { NgModule } from '@angular/core'; import { WebStorageModule } from '@efaps/ngx-store'; @NgModule({ imports: [ WebStorageModule, ], }) export class AppModule {}
配置
您在配置此模块时应考虑的事项 :
- 装饰对象已添加
.save()方法以方便地强制保存已修改的更改(由mutateObjects(中文(简体) ) - 对所有人的支持
Array改变数组对象值的方法可以禁用(由mutateObjects(中文(简体) ) - 对象突变对于对象比较来说可能很麻烦,所以您可以为单个字段通过配置此特性 装饰配置
- 您可能不会使用前缀( 设置为
''然而,我们建议使用它,因为它有助于避免与其他图书馆的冲突(可配置为:prefix(中文(简体) ) - 有三种方法可以清除 ngx 存储的数据 :
'all'- 完全清除当前存储器'prefix'- 删除由ngx-store前缀的所有变量'decorators'- 仅删除由装饰函数创建的变量( 不使用前缀时有用) 通过设置指定默认行为clearType,但可以直接将这个参数传入服务clear()方法.
- 实例
cookiesScope可见于 本评论
由于这个项目使用装饰功能,因此必须在命名为“自定义”的全局变量中提供自定义配置 NGXSTORE_CONFIG 在角应用程序加载之前。 以下是一些方法:
- 添加
<script>内index.html(在角源之前)<script> var NGXSTORE_CONFIG = { prefix: 'ngx_', // default: 'ngx_' clearType: 'prefix', // default: 'prefix' mutateObjects: true, // default: true debugMode: false, // you can enable debug logs if you ever meet any bug to localize its source cookiesScope: '', // what you pass here will actually prepend base domain cookiesCheckInterval: 0, // number in ms describing how often cookies should be checked for changes previousPrefix: 'angular2ws_', // you have to set it only if you were using custom prefix in old version ('angular2ws_' is a default value) }; </script> - 如果您使用 Web 软件包, 您可以在您的
webpack.js以这种方式存档 :plugins: [ new webpack.DefinePlugin({ NGXSTORE_CONFIG: JSON.stringify({ prefix: '', // etc }) }), ]
装饰器配置
装饰函数可以带配置对象到以下字段:
key: string- 变量下的密钥将被存储, 默认密钥是可变名称mutate: boolean- 例如,启用或禁用对象突变,默认取决于全局配置expires: Date- 为@CookieStorage()仅指定过期日期,无效=终生饼干
使用量
-
很容易用到装饰器 真正的魔法就是在这里发生的.
import { CookieStorage, LocalStorage, SessionStorage } from 'ngx-store'; export class MySuperComponent { // it will be stored under ${prefix}viewCounts name @LocalStorage() viewCounts: number = 0; // this under name: ${prefix}differentLocalStorageKey @LocalStorage('differentLocalStorageKey') userName: string = ''; // it will be stored under ${prefix}itWillBeRemovedAfterBrowserClose in session storage @SessionStorage({key: 'itWillBeRemovedAfterBrowserClose'}) previousUserNames: Array<string> = []; // it will be read from cookie 'user_id' (can be shared with backend) and saved to localStorage and cookies after change @LocalStorage() @CookieStorage({prefix: '', key: 'user_id'}) userId: string = ''; // it will be stored in a cookie named ${prefix}user_workspaces for 24 hours @CookieStorage({key: 'user_workspaces', expires: new Date(new Date().getTime() + 24 * 60 * 60 * 1000)}) userWorkspaces = []; constructor() { this.viewCounts++; this.userName = 'some name stored in localstorage'; this.previousUserNames.push(this.userName); for (let userName of this.previousUserNames) { console.log(userName); } this.previousUserNames.map(userName => userName.split('').reverse().join('')); } }各类变量共享: 装饰的变量可以容易地在不同类别之间共享,例如角构件(也在其被销毁后),而不需要为此创建新的服务.
import { LocalStorage, SharedStorage } from 'ngx-store'; export class HomeComponent { @SharedStorage() title: string = 'Homepage'; // it will be kept in temp memory until app reload @LocalStorage() userNote: string = 'Leave your note here'; // it will be read from and saved to localStorage constructor() { setTimeout(() => { console.log('userNote:', this.userNote); // it should be changed after user's visit to NestedComponent }, 5000); } } export class NestedComponent { @SharedStorage('title') homeTitle: string = ''; @LocalStorage() protected userNote: string = ''; constructor() { console.log('homeTitle:', this.homeTitle); // should print 'Homepage' console.log('userNote:', this.userNote); // should print userNote set in HomeComponent this.userNote = "You've visited NestedComponent!"; } }强制保存更改 : 如果您需要修改存储的对象, 而不是直接指派, 那么您可以利用
.save()强制保存的方法已更改。 示例import { CookieStorage, LocalStorage, SessionStorage, WebstorableArray } from 'ngx-store'; export class MySuperComponent { @LocalStorage() someObject: any = { c: 3 }; @SessionStorage() arrayOfSomethings: WebstorableArray<number> = <any>[0,1,2,3,4]; @CookieStorage({ mutate: false }) someCookie: {version?: number, content?: string} = {}; constructor() { this.someObject.a = 1; this.someObject['b'] = 2; delete this.someObject['c']; for (let i = 0; i < this.arrayOfSomethings.length; i++) { this.arrayOfSomethings[i] += i; } this.someCookie.version++; this.someCookie.content = 'please save me'; // upper changes won't be saved without the lines below this.someObject.save(); this.arrayOfSomethings.save(); this.someCookie = this.someCookie; // it looks weird, but also will do the job even without object mutation } }AoT 汇编中的有限生命周期课程: 当您应用程序中包含装饰变量的服务或组件被销毁时,有一个特殊的情况:
import { OnDestroy } from '@angular/core'; import { LocalStorage } from 'ngx-store'; export class SomeService implements OnDestroy { // implement the interface @LocalStorage() destroyedVariable: any = {}; ngOnDestroy() {} // event empty method is needed to allow ngx-store handle class destruction } -
使用 服务 用于管理您的数据 :
import { CookiesStorageService, LocalStorageService, SessionStorageService, SharedStorageService } from 'ngx-store'; export class MyService { constructor( localStorageService: LocalStorageService, sessionStorageService: SessionStorageService, cookiesStorageService: CookiesStorageService, sharedStorageService: SharedStorageService, ) { console.log('all cookies:'); cookiesStorageService.utility.forEach((value, key) => console.log(key + '=', value)); } public saveSomeData(object: Object, array: Array<any>) { this.localStorageService.set('someObject', object); this.sessionStorageService.set('someArray', array); this.localStorageService.keys.forEach((key) => { console.log(key + ' =', this.localStorageService.get(key)); }); } public clearSomeData(): void { this.localStorageService.clear('decorators'); // removes only variables created by decorating functions this.localStorageService.clear('prefix'); // removes variables starting with set prefix (including decorators) this.sessionStorageService.clear('all'); // removes all session storage data } }
说明: 总是在您正在使用的装饰属性中定义默认值 .
说明: 从不使用 for-in 环绕未过滤的已装饰阵列 .hasOwnProperty()。 。 。 .
说明: 请不要使用 ngx- store 循环结构, 因为此库使用 JSON. stringify 在保存前会编码数据 .
说明: 当您从 “' (空字符串) 中更改前缀时, 旧值将不会被自动删除, 以避免删除必要的数据 。 你应该手动处理 或者把Type设置到"所有"一段时间.
欢迎捐款!