a4-store
TypeScript icon, indicating that this package has built-in type declarations

8.0.0 • Public • Published

a4-store

7 Store for state management

How-To

Install

npm install a4-store

app.store.ts

import { Injectable } from '@angular/core';
import { InitialState, Store, Reducer } from 'a4-store';
 
interface State {
  data1: number;
  data2: number;
}
 
@InitialState<State>({
  data1: 123,
  data2: 9995
})
@Injectable({
  providedIn: 'root'
})
export class AppStore extends Store<State> {
 
  @Reducer()
  setData1(data: number): Partial<State> {
    return { data1: data };
  }
 
  @Reducer()
  setData2(data: number): Partial<State> {
    return { data2: data };
  }
 
}

my-sample.component.ts

import { Component, OnInit, OnDestroy } from '@angular/core';
import { AppStore } from './app.store';
import { Observable, Subscription } from 'rxjs';
 
@Component({
  selector: 'app-my-sample',
  templateUrl: './my-sample.component.html',
  styleUrls: ['./my-sample.component.css']
})
export class MySampleComponent implements OnInit, OnDestroy {
 
  data1: Observable<number>;
  data2: Observable<number>;
  subscriptions: Subscription[];
 
  constructor(private appStore: AppStore) {
    this.data1 = appStore.map(p => p.data1);
    this.data2 = appStore.map(p => p.data2);
  }
 
  ngOnInit() {
    this.subscriptions = [
      this.data1.subscribe(p => console.log(`Data 1 changes to ${p}`)),
      this.data2.subscribe(p => console.log(`Data 2 changes to ${p}`))
    ];
  }
 
  ngOnDestroy() {
    this.subscriptions.forEach(p => p.unsubscribe());
  }
 
  doClick() {
    this.appStore.setData1(this.appStore.state.data1 + 1);
    this.appStore.setData2(this.appStore.state.data2 - 1);
  }
 
}

Difference between .map and .select

Select will only fire the subscription when the current alue is different than the last while Map will fire the subscription when there is a new value set in the store.

Immutable Methods (protected)

These immutable methods can only be used within the store class.

immutableReplaceElement

Returning a new array with element at index being replaced by newElement.

immutableReplaceElement<T>(arrayT[], newElementT, indexnumber)T[]

immutableRemoveElement

Returning a new array with element at index being removed.

immutableRemoveElement<T>(arrayT[], indexnumber)T[]

immutableInsertElement

Returning a new array with element being inserted at specified index.

immutableInsertElement<T>(arrayT[], elementT, indexnumber)T[]

immutablePrependElement

Returning a new array with element inserted at the start (first element) of the given array.

immutablePrependElement<T>(arrayT[], elementT)T[]

immutableAppendElement

Returning a new array with element inserted at the end (last element) of the given array.

immutableAppendElement<T>(array: T[], element: T): T[]

Package Sidebar

Install

npm i a4-store

Weekly Downloads

6

Version

8.0.0

License

MIT

Unpacked Size

92.1 kB

Total Files

26

Last publish

Collaborators

  • cccheng