NGXS SHOWING A TOASTER.

Kaleemullah Nizamani
2 min readJul 9, 2020

This is my first article on medium, hopefully not the last one… I assume you understand Redux pattern in general and have written some code in NGXS. Here we are dealing with Heroes &Villain and will show the toaster based on the operation performed on the entity (Hero or Villain).

Here we have Actions for Heroes entity Basically they are CRUD Operations.

We are using toaster from Angular Material. This can be any toaster.

NGXS Actions have lifecycle. Since any potential action can be async we tag actions showing when they are “DISPATCHED”, “SUCCESSFUL”, “CANCELED” or “ERRORED”. This gives you the ability to react to actions at different points in their existence. Here we are showing toast for only success mainly heroes loaded,added,updated and deleted. If you want handle errors or any other case you can easily handle you have following pipes.

  • ofAction: triggers when any of the below lifecycle events happen
  • ofActionDispatched: triggers when an action has been dispatched
  • ofActionSuccessful: triggers when an action has been completed successfully
  • ofActionCanceled: triggers when an action has been canceled
  • ofActionErrored: triggers when an action has caused an error to be thrown
  • ofActionCompleted: triggers when an action has been completed whether it was successful or not (returns completion summary)

ENTITY_TYPE maintains key value pair where keys are our entities for which we want to show the toaster i.e Hero,Villain and values are their corresponding actions. We are using SubSink library by Ward Bell to quickly unsubscribe from Observables.

Next We need to make sure to inject the NgxsToasterService somewhere in your application for DI to hook things up so lets do that in app.module.ts

We can easily add the Villain entity and our modify ENTITY_TYPE as following.

Now finally in heroes component we inject he NgxsToasterService and call showToast method with value HERO which matches the ENTITY_TYPE.HERO so NgxsToasterService shows toaster for Hero. Thanks for reading that is it for now.

--

--