0.1.0-alpha.2 • Published 7 years ago
angular-component-rx v0.1.0-alpha.2
angular-component-rx
Store & redux service for angular components & directives that are intended for downstream consumption. Bascially @ngrx/store reworked for use via a given component's or directives's dependency injector.
Installation
$ npm install angular-component-rx --save
Usage
Counter component example:
import { Component } from '@angular/core';
import { Action, ComponentRxService, CONFIG, REDUCERS } from 'angular-component-rx';
// Counter component state model.
interface CounterState {
counter: number;
}
// Action type identifiers.
const incrementAction = 'INCREMENT';
const decrementAction = 'DECREMENT';
const resetAction = 'RESET';
// Counter reducer; perform state transition given current state and action (remember that states should stay immutable).
function counterReducer(state: number = 0, action: Action) {
switch (action.type) {
case incrementAction:
return state + 1;
case decrementAction:
return state - 1;
case resetAction:
return 0;
default:
return state;
}
}
// Counter component.
@Component({
encapsulation: ViewEncapsulation.Emulated,
selector: 'counter',
template: `<span>{{ counter | async }}</span>`,
// Consuming component must provide the following:
providers: [
// - Main store & redux service; glorified @ngrx/store wrapper ;).
ComponentRxService,
// - State reducers.
{
provide: REDUCERS,
useValue: { counter: counterReducer }
},
// - State & store configuration; see @ngrx/store.
{
provide: CONFIG,
useValue: {}
}
]
})
class CounterComponent {
public counter: Observable<number>;
public constructor(public service: ComponentRxService<CounterState>) {
// Data bound observable; see template.
this.counter = service.select('counter');
}
public increment(): void {
this.service.dispatch({ type: incrementAction });
}
public decrement(): void {
this.service.dispatch({ type: decrementAction });
}
public reset(): void {
this.service.dispatch({ type: resetAction });
}
}
API
Methods
getStateObservable(): State<T>
: Get state obervable used by service instance.- Exposed from @ngrx/store:
select<K>(mapFn: (state: T) => K): Store<K>
select<a extends keyof T>(key: a): Store<T[a]>
select(pathOrMapFn: ((state: T) => any) | string): Store<any>
- Select state slice; exposed subset of @ngrx/store overloads.
lift<R>(operator: Operator<T, R>): Store<R>
dispatch<V extends Action = Action>(action: V): void
next(action: Action): void
error(err: any): void
complete(): void
addReducer<State, Actions extends Action = Action>(key: string, reducer: ActionReducer<State, Actions>): void
removeReducer<Key extends keyof T>(key: Key): void
License
MIT