Search code examples
angularngxs

NgXS. DIfference between store.dispatch() and context.dispatch()?


In NgXS i have two ways to trigger an event from a state to another state:

  1. Call dispatch() from global Store
  2. Call dispatch() from StateContext object inside State

What's the difference between the two ways? Which method is better and why? E.g.

//== state action

@Action()
doAny(context: StateContext<MyContextModel>, payload: any): void {
  context.dispatch(new AnotherStateAction());
  // this._store.dispatch(new AnotherStateAction()); this code will do the same
}

Docs: https://www.ngxs.io/concepts/state#dispatching-actions-from-actions


Solution

  • As far as I understand, these methods use the same internal method of an InternalStateOperations service:

    • here and here for StateContextFactory that creates StateContext instances.
    • here and here for Store itself.

    That said, _store member is apparently treated as private (i.e. API is non-reliable for external use even for state class methods) so I suggest using StateContextinstance for dispatching.