简体   繁体   English

Angular 2:service 和 redux 的区别

[英]Angular 2: Difference between service and redux

redux 需要什么,因为我们还可以从服务中保存和获取数据,据我所知,我们还可以将数据获取和保存到服务中,这些服务可以被其他组件使用。

You don't need redux, but you do need a way to maintain state.您不需要 redux,但确实需要一种维护状态的方法。 A service will do, but in the end you will send up with something resembling redux or ngrx store.服务可以,但最终你会发送类似 redux 或 ngrx store 的东西。

Consider the challenge.考虑挑战。 You have data coming in asynchronously.您有异步传入的数据。 You want it reactive.您希望它具有反应性。 You want to have error handling.您想要进行错误处理。 You want to have waiting states as data is updated.您希望在数据更新时具有等待状态。 You have cascading scenarios where one event triggers multiple actions, each with its own latency and error paths.您有级联场景,其中一个事件触发多个操作,每个操作都有自己的延迟和错误路径。

And you want to set up a pattern that can be used in multiple components.并且您想设置一个可以在多个组件中使用的模式。

Victor Savkin has a way of doing this with observables which is very slick. Victor Savkin 有一种非常巧妙的 observables 方法。 Ngrx has another way. Ngrx 有另一种方式。

I wrote a moderately complex component using a service.我使用服务编写了一个中等复杂的组件。 It worked ok.它工作正常。 Hours would disappear into tracking down some odd situations where the state was undefined and threw errors.数小时将消失以跟踪一些奇怪的情况,其中状态未定义并引发错误。 I was getting far too much into the weeds to have something reusable as a pattern.我对杂草太过分了,以至于无法将一些可重复使用的东西作为一种模式。 And the result was fragile and brittle.结果是脆弱易碎。 It wasn't fully reactive, and to make it was proving extremely difficult and time consuming.它不是完全反应式的,并且证明它非常困难和耗时。 I ported it to ngrx, and once the learning curve is surmounted, which isn't trivial, the code became simpler and fully instrumented allowing quick debugging.我将它移植到 ngrx,一旦克服了学习曲线,这不是微不足道的,代码变得更简单,并且完全检测允许快速调试。

YMMV.天啊。

Victor Savkin has an article on how to maintain state Victor Savkin 有一篇关于如何维护状态的文章

A service is an Angular implementation detail.服务是一个 Angular 实现细节。 Whereas redux is an architectural concept.而 redux 是一个架构概念。 The two are not directly comparable.两者没有直接可比性。

If you are interested how redux can be applied to Angular, I would recommend reading the Comprehensive Introduction to @ngrx/store .如果您对如何将 redux 应用于 Angular 感兴趣,我建议您阅读@ngrx/store综合介绍

A service is a Angular feature that will allow user to manage their common methods and properties.But the state pattern which provide the structure way to manage our application state ( properties that commonly used through the application ).服务是一个 Angular 特性,它将允许用户管理他们的常用方法和属性。但是状态模式提供了管理我们的应用程序状态(通过应用程序常用的属性)的结构方式。

If you are interested to lean Angular state pattern i would recommend @ngrx/store && @ngxs/store .如果您有兴趣学习 Angular 状态模式,我会推荐@ngrx/store && @ngxs/store both will be a good one.两者都会是好的。 i would suggest ngxs which is more simple than to compare @ngrs/store implementation and it have the clear documentation to learn.我会建议ngxs ,它比比较@ngrs/store实现更简单,并且它有清晰的文档可供学习。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM