# @efaps/ngx-store 中文文档

规范地址：https://npmcn.com/package/%40efaps/ngx-store/

版本：11\.0\.0
npm 元数据更新时间：2025-06-04T16:53:15.835Z
中文译文更新时间：2026-11-13T08:04:43.369Z
软件包许可：ISC

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40efaps/ngx-store
原文对照：https://npmcn.com/package/%40efaps/ngx-store/?lang=original
项目主页：https://github.com/eFaps/ngx-store
源码仓库：https://github.com/eFaps/ngx-store

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：139 kB，5 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- 运行依赖：6 个
- peer 依赖：@angular/common ^18\.0\.0 \|\| ^19\.0\.0 \|\| ^20\.0\.0，@angular/core ^18\.0\.0 \|\| ^19\.0\.0 \|\| ^20\.0\.0
- 首次发布：2020-04-29T00:08:43.561Z
- 最新版本发布：2025-06-04T16:53:15.662Z
- 近 30 天下载量：4072（2026-10-13 至 2026-11-11，npm 官方下载统计）
- 已发布版本数：22（近 12 个月 0 个）

## 中文简介

这个图书馆添加了装饰器 使得它非常容易 _自动_ 使用 HTML5 保存并恢复变量 `localStorage` 财务报告和审定财务报表 `sessionStorage`。它也提供Angular-Injectable session-和本地服务.

## 安装

```sh
npm install @efaps/ngx-store
```

也可以使用：`pnpm add @efaps/ngx-store`、`yarn add @efaps/ngx-store`、`bun add @efaps/ngx-store`

## README

# 角存储

### 饼干、会话和本地版的装饰和服务

这个图书馆添加了装饰器 使得它非常容易 _自动_ 使用 HTML5 保存并恢复变量 `localStorage` 财务报告和审定财务报表 `sessionStorage`。它也提供Angular-Injectable session-和本地服务.

## 包含什么?

-   相当容易使用和配置的装饰函数(参见 [装饰器配置](https://npmcn.com/package/%40efaps/ngx-store/#readme-decorators-config):
    -   `@LocalStorage()` - 在 HTML5 本地服务器中保存变量
    -   `@SessionStorage()` - 在 HTML5 会话中保存变量Storage
    -   `@CookieStorage()` - 将变量保存为饼干
    -   `@SharedStorage()` - 将可跨类共享的变量保留在临时记忆中
    -   `@TempStorage()` - 别名用于 `SharedStorage`
-   可注射 `LocalStorageService`, (中文(简体) ), `SessionStorageService`, (中文(简体) ), `CookiesStorageService` 财务报告和审定财务报表 `SharedStorageService` (单位:千美元)[这里读更多](https://npmcn.com/package/%40efaps/ngx-store/src/service#angular-storage)(中文(简体) )
-   可能性 [监听存储更改](https://github.com/zoomsphere/ngx-store/tree/master/src/service#listening-to-changes)
-   简单配置( 见 [\# 配置 #](https://npmcn.com/package/%40efaps/ngx-store/#readme-configuration) 页: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`(中文(简体) )
-   删除已折旧( 自 v0. 5 起) `WEBSTORAGE_CONFIG`
-   `@SharedStorage` 现在有别名 `@TempStorage`
-   介绍 [构建器模式](https://github.com/zoomsphere/ngx-store/tree/master/src/service#builder-pattern)
-   增加单位测试覆盖率
-   存储事件的修改

## 即将来临( TODO)

-   从外部取出密钥的存储事件
-   存储事件测试(接受PR)
-   接受作为终止日期的时机(接受公关)
-   管理 cookie 的更多选项
-   支持设置和地图
-   保存数据的编码
-   从配置 [npm 配置](https://www.npmjs.com/package/config)'文件 (?) (中文(简体) )
-   自动处理所有使用的数据操作 [代理服务器](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) (ES6) (中文(简体) )

## 安装

1.  下载库 : `npm i @efaps/ngx-store --save` 或者说 `npm i ngx-store@RC` 用于最新版本
2.  导入您的 WebStorage 模块 `app.module.ts`数字 :
    
    ```typescript
    import { NgModule } from '@angular/core';
    import { WebStorageModule } from '@efaps/ngx-store';
    
    @NgModule({
      imports: [
        WebStorageModule,
      ],
    })
    export class AppModule {}
    ```
    

## 配置

您在配置此模块时应考虑的事项 :

-   装饰对象已添加 `.save()` 方法以方便地强制保存已修改的更改(由 `mutateObjects`(中文(简体) )
-   对所有人的支持 `Array` 改变数组对象值的方法可以禁用(由 `mutateObjects`(中文(简体) )
-   对象突变对于对象比较来说可能很麻烦,所以您可以为单个字段通过配置此特性 [装饰配置](https://npmcn.com/package/%40efaps/ngx-store/#readme-decorators-config)
-   您可能不会使用前缀( 设置为 `''`然而,我们建议使用它,因为它有助于避免与其他图书馆的冲突(可配置为: `prefix`(中文(简体) )
-   有三种方法可以清除 ngx 存储的数据 :
    -   `'all'` - 完全清除当前存储器
    -   `'prefix'` - 删除由ngx-store前缀的所有变量
    -   `'decorators'` - 仅删除由装饰函数创建的变量( 不使用前缀时有用) 通过设置指定默认行为 `clearType`,但可以直接将这个参数传入服务 `clear()` 方法.
-   实例 `cookiesScope` 可见于 [本评论](https://github.com/zoomsphere/ngx-store/blob/master/src/utility/storage/cookies-storage.ts#L125)

由于这个项目使用装饰功能,因此必须在命名为“自定义”的全局变量中提供自定义配置 `NGXSTORE_CONFIG` 在角应用程序加载之前。 以下是一些方法:

1.  添加 `<script>` 内 `index.html` (在角源之前)
    
    ```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>
    ```
    
2.  如果您使用 Web 软件包, 您可以在您的 `webpack.js` 以这种方式存档 :
    
    ```javascript
    plugins: [
      new webpack.DefinePlugin({
        NGXSTORE_CONFIG: JSON.stringify({
          prefix: '', // etc
        })
      }),
    ]
    ```
    

## 装饰器配置

装饰函数可以带配置对象到以下字段:

-   `key: string` - 变量下的密钥将被存储, 默认密钥是可变名称
-   `mutate: boolean` - 例如,启用或禁用对象突变,默认取决于全局配置
-   `expires: Date` - 为 `@CookieStorage()` 仅指定过期日期,无效=终生饼干

## 使用量

1.  很容易用到装饰器 真正的魔法就是在这里发生的.
    
    ```typescript
    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(''));
      }
    }
    ```
    
    **各类变量共享:** 装饰的变量可以容易地在不同类别之间共享,例如角构件(也在其被销毁后),而不需要为此创建新的服务.
    
    ```typescript
    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()` 强制保存的方法已更改。 示例
    
    ```typescript
    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 汇编中的有限生命周期课程:** 当您应用程序中包含装饰变量的服务或组件被销毁时,有一个特殊的情况:
    
    ```typescript
    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.  使用 [服务](https://npmcn.com/package/%40efaps/ngx-store/src/service#angular-storage) 用于管理您的数据 :
    
    ```typescript
    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设置到"所有"一段时间.

**欢迎捐款!**

## 常见问题

### @efaps/ngx-store 是什么？

这个图书馆添加了装饰器 使得它非常容易 自动 使用 HTML5 保存并恢复变量 localStorage 财务报告和审定财务报表 sessionStorage。它也提供Angular-Injectable session-和本地服务\.

### 如何安装 @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 和提交记录判断。

