ngrx, How to have a starting state from an api?

谁说胖子不能爱 提交于 2019-12-22 13:59:42

问题


I have my reducer with a starting state of an empty array:

folderReducer(state:Array<Folder> = [], action: Action)

I'd like to populate the starting state, so when I do

store.subscribe(s => ..)

The first item I get comes from the database. I assume the way of doing this is with ngrx/effects, but I'm not sure how.


回答1:


Your store always has the initial state, that you define in the reducer-function. The initial states main purpose is to ensure that the application is able to start up and not run into any null-pointer-exceptions. And also it sets up your application to start making the first api-calls ect. - so you can think of it as a technical initial state.

If you want to fill your store with api-data on the startup, you would do that on the same way that you add/modify data during any other action - just that the action of "initially loading data" is not triggered by some user-interaction but through:

  • either when your root-component loads
  • or as part of a service in the constructor

In case you want to prevent specific components from showing anything until your API-call is done, you would have to adjust the display-components to display or hide data based on your state (e.g. by implementing a flag in your satet initialDataLoaded).




回答2:


A dynamic initial state is now supported, see: https://github.com/ngrx/platform/blob/master/docs/store/api.md#initial-state-and-ahead-of-time-aot-compilation

Also see: https://github.com/ngrx/platform/issues/51

I would only do this if the database is local, otherwise the request will hold up loading of the application.



来源:https://stackoverflow.com/questions/42517257/ngrx-how-to-have-a-starting-state-from-an-api

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!