由于双向数据绑定,数据始终同步时,在 Angular 中使用 NgRx 的原因是什么?

What is the reason to use NgRx in Angular when data is always synced due to two way data binding?

NgRx,这是 Redux for React 的 Angular 版本,用于状态管理。在 React 中,状态管理可能会变得复杂,而 Redux 可以提供帮助。对于 Angular,这不应该是这种情况,因为由于双向数据绑定,所有内容都已同步。

不过,我看到很多项目都在使用 NgRx。

为什么会这样?

双向绑定和状态管理是完全不同的概念。

考虑这个例子。

假设您有一个网络应用程序,您在多个地方使用登录用户的名称。您不必每次都从服务器查询名称,而是将其放在 NgRx 存储中并从那里查询。这样您就可以节省从服务器获取数据的时间和资源。这与双向绑定无关。

这是一个非常简单的示例,不保证 NgRx。但是让我们玩我们拥有的吧。

我们可以通过注入服务和可观察对象来做到这一点吗?我们当然可以。

但您的服务除了向后端发出 get rest 调用外,还需要维护状态。考虑到数据也是从多个数据源异步传入的。假设您希望在更新名称时进行一些错误处理。假设更新名称触发多个异步操作,每个操作都有自己的延迟和错误处理。假设多个组件使用状态值。当然,您可以使用服务和可观察对象来编写所有这些。最后,您的代码可能看起来类似于使用 Redux。

NgRx 代表 Angular 响应式扩展 。简而言之,它是一个基于Redux模式的状态管理系统。这将帮助您在更大的 angular 应用程序中管理应用程序状态。

它将按预期工作,因为所有组件都可以从特定服务获取或设置所需数据。但是,实际问题是 如果我们刷新页面,我们将丢失存储在 angular 服务中的应用程序状态

所以,如果我们使用angular服务来保存应用状态,就需要使用后端来保存应用状态。 然后,我们应该在页面重新加载时从后端获取状态(持久状态)。

众所周知,状态不仅仅是作为用户数据的数据,它会决定屏幕上应该显示什么。对于较小的应用程序,可以使用组件和服务来进行应用程序状态管理。但是,当我们的应用程序变得复杂和庞大时,管理应用程序状态将变得困难。

Redux is a state management pattern and a library to implement that pattern into any application.

The main idea behind the management of the state using the Redux pattern is that we have a single central store to keep all applications state.

We can consider this store as a large javascript object that holds all the data of different parts of our application needs.

Our components and services can communicate with each other. But they receive their states from this central store.

We can say the store is the single source of truth that manages the entire application state.

有关更多信息,请单击 here

参考:https://www.c-sharpcorner.com/article/state-management-in-angular-using-ngrx/

NgRx 网站有以下内容: Why use NgRx Store for State Management?

它说:

you might use NgRx when you build an application with a lot of user interactions and multiple data sources, or when managing state in services are no longer sufficient.

然后继续:

A good guideline that might help answer the question, "Do I need NgRx Store?" is the SHARI principle:

  • Shared: state that is accessed by many components and services.
  • Hydrated: state that is persisted and rehydrated from external storage.
  • Available: state that needs to be available when re-entering routes.
  • Retrieved: state that must be retrieved with a side-effect.
  • Impacted: state that is impacted by actions from other sources.

它还提醒您:

However, realizing that using NgRx Store comes with some tradeoffs is also crucial. It is not meant to be the shortest or quickest way to write code. It also encourages the usage of many files.

我会尝试提供一个更简单的解释:

双向数据绑定的问题在于,在现实生活中的应用程序中,您通常最终会拥有复杂的多级组件树。

有些组件在某个时候只会存在,以便从它们的父级获取数据并将其传递给它们的子级。当您需要更改某些内容或进行一些简单的重构时 - E.G.移动一个组件或在层次结构中引入一个新组件——你将有很多不必要的重新布线要做只是为了保持数据绑定工作。您最终会因为要修复的问题太多 inputs/outputs 而放弃即使是简单的重构。

这根本不是 NgRx 的问题。