6

Let's say we an action SyncUserData, which returns observable that listen to changes from the database. Whenever there's a change, the action dispatches the action new PatchUserData(newData).

The SyncUserData action is dispatched (only once) from ngxsOnInit of the state.

In a different section (e.g., component), I want to do something whenever the action PatchUserData is dispatching. Something like this:

this.store.onDispatch(PatchUserData).subscribe();

I was looking a bit in the source, and I didn't find something similar to my example.

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
Eliya Cohen
  • 10,716
  • 13
  • 59
  • 116

2 Answers2

3

An alternative to subscribing to the state directly is to use the NGXS action stream to be notified when a specific action has been dispatched/completed see the documentation for action handlers.

From the official doco:

@Component({ ... })
export class CartComponent {
  constructor(private actions$: Actions) {}

  ngOnInit() {
    this.actions$.pipe(ofActionSuccessful(CartDelete)).subscribe(() => alert('Item deleted'));
  }
}
Garth Mason
  • 7,611
  • 3
  • 30
  • 39
2

You don't need to subscribe to a certain event in your case, you can subscribe to userData in your store and have the lastest version of it no matter whatever action changed it. Modify next sample according to your data models and subscribe to observable:

import { Select } from '@ngxs/store';

@Select(({ userData }: AppState) => userData)
  userData$!: Observable<UserData>;

More on select: https://ngxs.gitbook.io/ngxs/concepts/select

Yevgen
  • 4,519
  • 3
  • 24
  • 34