This package allows you to get rid of actions. You can use decorators to register actions directly in your state, you don't have to create any actions in your project (until you really need them), as they don't give any profit, only bring extra boilerplate files.
Concepts
Compare these diagrams, we've simplified Redux flow and threw out unnecessary middleware:
📦 Install
To install @ngxs-labs/emitter run the following command:
npm install @ngxs-labs/emitter
# or if you use yarn
yarn add @ngxs-labs/emitter
🔨 Usage
Import the module into your root application module:
import { NgModule } from '@angular/core';
import { NgxsModule } from '@ngxs/store';
import { NgxsEmitPluginModule } from '@ngxs-labs/emitter';
@NgModule({
imports: [
NgxsModule.forRoot(states),
NgxsEmitPluginModule.forRoot()
]
})
export class AppModule {}
Receiver
Receiver is a basic building block. @Receiver() is a function that allows you to decorate static methods in your states for further passing this method to the emitter:
import { State, StateContext } from '@ngxs/store';
import { Receiver } from '@ngxs-labs/emitter';
@State<number>({
name: 'counter',
defaults: 0
})
export class CounterState {
@Receiver()
public static increment({ setState, getState }: StateContext<number>) {
setState(getState() + 1);
}
@Receiver()
public static decrement({ setState, getState }: StateContext<number>) {
setState(getState() - 1);
}
}
Emitter
Emitter is basically a bridge between your component and receivers. @Emitter() is a function that decorates properties defining new getter and gives you an access to the emittable interface:
import { Component } from '@angular/core';
import { Select } from '@ngxs/store';
import { Emitter, Emittable } from '@ngxs-labs/emitter';
import { Observable } from 'rxjs';
import { CounterState } from './counter.state';
@Component({
selector: 'app-counter',
template: `
<ng-container *ngIf="counter$ | async as counter">
<h3>Counter is {{ counter }}</h3>
</ng-container>
<button (click)="increment.emit()">Increment</button>
<button (click)="decrement.emit()">Decrement</button>
`
})
export class CounterComponent {
@Select(CounterState)
public counter$: Observable<number>;
// Use in components to emit asynchronously payload
@Emitter(CounterState.increment)
public increment: Emittable<void>;
@Emitter(CounterState.decrement)
public decrement: Emittable<void>;
}
Custom types
You can define custom types for debbuging purposes (works with @ngxs/logger-plugin):
import { Component } from '@angular/core';
import { Select } from '@ngxs/store';
import { Emitter, Emittable } from '@ngxs-labs/emitter';
import { Observable } from 'rxjs';
import { AnimalsState } from './animals.state';
@Component({
selector: 'app-root',
template: `
<p *ngFor="let animal of (animals$ | async)">{{ animal }}</p>
<button (click)="addAnimals()">Add animals</button>
`
})
export class AppComponent {
@Select(AnimalsState)
public animals$: Observable<string[]>;
@Emitter(AnimalsState.addAnimal)
private addAnimal: Emittable<string>;
public addAnimals(): void {
this.addAnimal.emitMany(['panda', 'zebra', 'monkey']);
}
}
Dependency injection
Assume you have to make some API request and load some data from your server, it is very easy to use services with static methods, Angular provides an Injector class for getting instances by reference:
import { Injector } from '@angular/core';
import { State, StateContext } from '@ngxs/store';
import { Receiver } from '@ngxs-labs/emitter';
import { tap } from 'rxjs/operators';
interface Todo {
id: number;
title: string;
completed: boolean;
}
@State<Todo[]>({
name: 'todos',
defaults: []
})
export class TodosState {
// ApiService is defined somewhere...
private static api: ApiService;
constructor(injector: Injector) {
TodosState.api = injector.get<ApiService>(ApiService);
}
@Receiver()
public static getTodos({ setState }: StateContext<Todo[]>) {
// If `ApiService.prototype.getTodos` returns an `Observable` - just use `tap` operator
return this.api.getTodos().pipe(
tap((todos) => setState(todos))
);
}
// OR
@Receiver()
public static getTodos({ setState }: StateContext<Todo[]>) {
// If `ApiService.prototype.getTodos` returns a `Promise` - just use `then`
return this.api.getTodos().then((todos) => setState(todos));
}
}
If you work with promises - we advice you to use async/await approach, because method marked with async keyword will automatically return a Promise, you will not get confused if you missed return keyword somewhere:
As you may know - actions in NGXS have own lifecycle. We also provide RxJS operators that give you the ability to react to actions at different points in their existence:
ofEmittableDispatched: triggers when an emittable target has been dispatched
ofEmittableSuccessful: triggers when an emittable target has been completed successfully
ofEmittableCanceled: triggers when an emittable target has been canceled
ofEmittableErrored: triggers when an emittable target has caused an error to be thrown
Below is just a simple example how to use those operators:
import { State, StateContext } from '@ngxs/store';
import { Receiver } from '@ngxs-labs/emitter';
import { throwError } from 'rxjs';
@State<number>({
name: 'counter',
defaults: 0
})
export class CounterState {
@Receiver()
public static increment({ setState, getState }: StateContext<number>) {
setState(getState() + 1);
}
@Receiver()
public static decrement({ setState, getState }: StateContext<number>) {
setState(getState() - 1);
}
@Receiver()
public static multiplyBy2({ setState, getState }: StateContext<number>) {
setState(getState() * 2);
}
@Receiver()
public static throwError() {
return throwError(new Error('Whoops!'));
}
}
Import operators in your component and pipe Actions service:
You can easily provide an interaction between different states using ER. Imagine such simple state that stores information if success and error messages exist: