@efaps/ngx-store

中文文档
11.0.0发布于 2025/06/05ISCTypeScriptES Module近 30 天下载 4072

This library adds decorators that make it super easy to automagically save and restore variables using HTML5's localStorage and sessionStorage. It also provides Angular-Injectable Session- and LocalStorageService.

原始使用文档
文档目录8 节
  1. Decorators and services for cookies, session- and localStor…
  2. What's included?
  3. CHANGELOG
  4. Upcoming (TODO)
  5. Installation
  6. Configuration
  7. Decorators config
  8. Usage

Angular Storage

Decorators and services for cookies, session- and localStorage

This library adds decorators that make it super easy to automagically save and restore variables using HTML5's localStorage and sessionStorage. It also provides Angular-Injectable Session- and LocalStorageService.

What's included?

  • Decorator functions that are pretty easy to use and configure (see Decorators config):
    • @LocalStorage() - to save variable in HTML5 localStorage
    • @SessionStorage() - to save variable in HTML5 sessionStorage
    • @CookieStorage() - to save variable as a cookie
    • @SharedStorage() - to keep variable in temporary memory that can be shared across classes
    • @TempStorage() - alias for SharedStorage
  • Injectable LocalStorageService, SessionStorageService, CookiesStorageService and SharedStorageService (read more here)
  • Possibility of listening to storage changes
  • Easy configuration (see #configuration section)
  • Tests coverage

CHANGELOG

v3.0.0 - support for Angular 9

Version from Zoomsphere

v2.1.0 - support for Angular 7 & TypeScript 3

v2.0.0 - support for Angular 6 (RxJS v6)

v1.4.x

  • standardized behavior for:
    • more than 1 decorator, e.g. in @LocalStorage() @CookieStorage() variable: any; CookieStorage (decorator closer to variable) has higher priority, hence the value will be read from cookies only. The cookie value will be saved in localStorage regardless of its content to keep consistency.
    • WebStorageService.clear('all') - now will remove everything except ngx-store's config (stored in localStorage)
  • removed deprecated (since v0.5) WEBSTORAGE_CONFIG
  • @SharedStorage has now alias @TempStorage
  • introduced builder pattern
  • added unit tests coverage
  • fixes for storage events

Upcoming (TODO)

  • Storage events for keys removed from outside
  • Tests for storage events (accepting PRs)
  • Accepting Moment's instances as expiration date (accepting PRs)
  • More options for managing cookies
  • Support for Set and Map
  • Encoding of saved data
  • Take configuration from npm config's file (?)
  • Automatically handle all data manipulations using Proxy (ES6)

Installation

  1. Download the library: npm i @efaps/ngx-store --save or npm i ngx-store@RC for latest version
  2. Import the WebStorageModule in your app.module.ts:
    import { NgModule } from '@angular/core';
    import { WebStorageModule } from '@efaps/ngx-store';
    
    @NgModule({
      imports: [
        WebStorageModule,
      ],
    })
    export class AppModule {}
    

Configuration

Things you should take into consideration while configuring this module:

  • Decorated objects have added .save() method to easily force save of made changes (configurable by mutateObjects)
  • Support for all Array methods that change array object's value can be disabled (configurable by mutateObjects)
  • Object mutation can be troublesome for object comparisons, so you can configure this feature for single field passing decorator config
  • You may not use prefix (by setting it to ''), however we recommend to use it, as it helps avoid conflicts with other libraries (configurable by prefix)
  • There are 3 ways to clear ngx-stored data:
    • 'all' - completely clears current Storage
    • 'prefix' - removes all variables prefixed by ngx-store
    • 'decorators' - removes only variables created by decorating functions (useful when not using prefix) Default behaviour is specified by setting clearType, but it's possible to pass this parameter directly into service clear() method.
  • Examples for cookiesScope can be found in this comment

As this project uses decorating functions, it is important to provide custom configuration in global variable named NGXSTORE_CONFIG before Angular application load. Here are some ways to do it:

  1. Add <script> in index.html (before Angular sources)
    <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>
    
  2. If you use webpack, you can provide global variable in your webpack.js file this way:
    plugins: [
      new webpack.DefinePlugin({
        NGXSTORE_CONFIG: JSON.stringify({
          prefix: '', // etc
        })
      }),
    ]
    

Decorators config

Decorating functions can take config object with the following fields:

  • key: string - key under the variable will be stored, default key is the variable name
  • mutate: boolean - enable or disable object mutation for instance, default depends on global config
  • expires: Date - for @CookieStorage() only, specifies expiration date, null = lifetime cookie

Usage

  1. Pretty easy to use decorators. Here is where the real magic happens.

    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(''));
      }
    }
    

    Sharing variables across classes: Decorated variables can be easily shared across different classes, e.g. Angular Components (also after their destruction) without need to create new service for this purpose.

    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!";
      }
    }
    

    Force save changes: If you need to modify stored object by not a direct assignment, then you can take advantage of .save() method to force save made changes. Example:

    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
       }
    }
    

    Limited lifecycle classes in AoT compilation: There is a special case when Service or Component in your application containing decorated variable is being destroyed:

    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
    }
    
  2. Use the services to manage your data:

    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
      }
    }
    

Note: Always define default value at the property you are using decorator.

Note: Never use for-in loop on decorated Arrays without filtering by .hasOwnProperty().

Note: Please don't ngx-store circular structures as this library uses JSON.stringify to encode data before saving.

Note: When you change prefix from '' (empty string) old values won't be removed automatically to avoid deleting necessary data. You should handle it manually or set clearType to 'all' for some time.

Contributions are welcome!

版本与发布记录

@efaps/ngx-store 共发布 22 个版本,首次发布于 2020/04/29;过去 12 个月发布了 0 个版本。

版本发布日期距今
11.0.0latest2025/06/051.4 年前
10.1.02025/04/101.6 年前
10.0.02025/01/141.8 年前
9.0.02024/05/312 年前
8.0.02023/12/052 年前
7.1.02023/08/223 年前

关于 @efaps/ngx-store 的常见问题

@efaps/ngx-store 是什么?

This library adds decorators that make it super easy to automagically save and restore variables using HTML5's localStorage and sessionStorage. It also provides Angular-Injectable Session- and LocalStorageService.

如何安装 @efaps/ngx-store?

在项目目录运行 npm install @efaps/ngx-store,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@angular/common(^18.0.0 || ^19.0.0 || ^20.0.0)、@angular/core(^18.0.0 || ^19.0.0 || ^20.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@efaps/ngx-store 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@efaps/ngx-store 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@efaps/ngx-store 可以商用吗?

@efaps/ngx-store 使用 ISC 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@efaps/ngx-store 的下载量有多少?

根据 npm 官方下载统计,@efaps/ngx-store 在 2026/10/13 – 2026/11/11 这 30 天内被下载 4,072 次,日均约 136 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@efaps/ngx-store 还在维护吗?

最新版本 11.0.0 发布于 2025/06/05(1.4 年前);至今共发布 22 个版本,其中过去 12 个月发布了 0 个;首次发布于 2020/04/29。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。