a4-store
v8.0.0
Published
Simple State Management Reactive Store
Downloads
1
Readme
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>(array: T[], newElement: T, index: number): T[]
immutableRemoveElement
Returning a new array with element at index being removed.
immutableRemoveElement<T>(array: T[], index: number): T[]
immutableInsertElement
Returning a new array with element being inserted at specified index.
immutableInsertElement<T>(array: T[], element: T, index: number): T[]
immutablePrependElement
Returning a new array with element inserted at the start (first element) of the given array.
immutablePrependElement<T>(array: T[], element: T): 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[]