maku_at
maku_at

Reputation: 1689

Ngxs - How to prepopulate state on application load

I would like to set the ngxs state on application load. What would be the best way to do this?

e.g. resolve the state object in an angular APP_INITIALIZER and then ???

Upvotes: 4

Views: 2765

Answers (2)

Garth Mason
Garth Mason

Reputation: 8011

You could make the HTTP call to load data for the state via the ngxsOnInit lifecycle hook see the lifecycle documentation here.

In my usage of NGXS we've typically had our states respond to a particular action e.g. UserLoggedIn to load their initial data from an external service

We needed to wait on this action for two reasons:

  • the HTTP services we called needed the auth token returned by Login to authenticate.
  • in many cases the services would return 'default' data that was user specific.

Upvotes: 2

foxcodes
foxcodes

Reputation: 31

You can either use defaults from the stat decorator (if it's the same one all the time on startup)or just populate the state in APP_INITIALIZER using normal store.dispatch

Upvotes: 0

Related Questions