@ngify/store
TypeScript icon, indicating that this package has built-in type declarations

1.5.3 • Public • Published

@ngify/store

version Node.js CI License CodeFactor 简体中文

A simple state manager based on decorator and rxjs.

Concept

There is a Store in the application that stores some global States. Every state is an object. Objects have properties that are the values of this state, and objects have methods that can modify the value of the object.
By convention, only methods of the state class object can modify the state value.

API

For the full API definition, please visit https://ngify.github.io/ngify.

Install

npm i @ngify/store

Usage

Definition state:

import { Action, State } from '@ngify/store';

// Decorate User as a state class using the State decorator.
@State()
export class User {
  constructor(
    public name: string,
    public age: number,
    public weight: number
  ) { }

  // Decorating with the Action decorator involves methods that modify state.
  @Action()
  changeName(name: string) {
    this.name = name;
  }

  // Action decorator has an optional property (ActionName), which defaults to the method name.
  @Action()
  growUp() {
    this.age++;
  }

  // You can also customize the action name.
  @Action('lose-weight')
  loseWeight() {
    this.weight -= 5;
  }

  // When state needs to be modified asynchronously, async/await is required or a Promise/Observable is returned
  @Action()
  async asyncLoseWeight() {
    await new Promise(resolve => {
      this.weight -= 10;
      resolve();
    });
  }

  log() {
    console.log(this);
  }
}

Create state at the application entry point:

import { User } from './xxx';

...
new User('Jack', 15, 100);
...

Listen for state change:

import { getStore } from '@ngify/store';
import { map } from 'rxjs';
import { User } from './xxx';

const store = getStore();

store.on(User).subscribe(o => {
  console.log('User: changed', o);
});

store.on(User, 'changeName').pipe(
  map(o => o.name)
).subscribe(name => {
  console.log('User: change name', name);
});

store.on(User, 'lose-weight').subscribe(o => {
  console.log('User: weight loss success', o);
});

Get state object:

import { getStore } from '@ngify/store';
import { User } from './xxx';

const user = getStore().get(User);
user.changeName('Jobs');

Dependencies (1)

Dev Dependencies (0)

    Package Sidebar

    Install

    npm i @ngify/store

    Weekly Downloads

    25

    Version

    1.5.3

    License

    MIT

    Unpacked Size

    26.3 kB

    Total Files

    23

    Last publish

    Collaborators

    • hyperlife1119