ER is a new pattern that provides the opportunity to feel free from actions
🚀 See it in action on Stackblitz
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:
:package: 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
:hammer: Usage
Import the module into your root application module:
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:
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:
Custom types
You can define custom types for debbuing purposes (works with @ngxs/logger-plugin
):
Actions
If you still need actions - it is possible to pass an action as an argument into @Receiver()
decorator:
Emitting multiple value
It's also possible to emit multiple values, just define your state:
And use emitMany
method from Emittable
object:
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:
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:
Lifecycle
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 dispatchedofEmittableSuccessful
: triggers when an emittable target has been completed successfullyofEmittableCanceled
: triggers when an emittable target has been canceledofEmittableErrored
: triggers when an emittable target has caused an error to be thrown
Below is just a simple example that uses those operators:
Import operators in component and pipe Actions
service:
Testing
It's very easy to write unit tests using ER concept: