ngrx,如何从api获得起始状态? [英] ngrx, How to have a starting state from an api?

查看:49
本文介绍了ngrx,如何从api获得起始状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的reducer的初始状态为空数组

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 => ..)

我得到的第一项来自数据库.我认为使用ngrx/effects可以做到这一点,但是我不确定该怎么做.

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.

推荐答案

您的商店始终具有您在化简函数中定义的初始状态. 初始状态的主要目的是确保应用程序能够启动,并且不会遇到任何空指针异常.并设置您的应用程序以开始进行第一个api调用. -因此您可以将其视为技术初始状态.

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.

如果您想在启动时使用api数据填充商店,则可以采用与其他操作期间添加/修改数据的方式相同的方式-只是初始加载数据"的操作不是通过某些用户交互触发的,而是通过以下方式触发的:

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:

  • 在加载根组件时要么
  • 或作为构造函数中服务的一部分

如果要防止特定组件在完成API调用之前不显示任何内容,则必须调整显示组件以根据您的状态显示或隐藏数据(例如,通过在satet中实现标志initialDataLoaded).

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).

这篇关于ngrx,如何从api获得起始状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆