Angular2 的服务应该是无状态的吗? [英] Are Angular2's services supposed to be stateless?

查看:31
本文介绍了Angular2 的服务应该是无状态的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自 Java 世界,那里的服务通常是无状态的.Angular2 中的服务也应该是无状态的吗?或者我们可以简单地存储状态,因为我们不必像 Java 示例中那样关心并发线程访问?

I come from Java world where services are commonly meant to be stateless. Should be services in Angular2 also stateless? Or can we simply store the state, because we do not have to care about concurrent thread access as in Java example?

https://angular.io/docs/ts/latest/guide/router.html#!#teach-authguard-to-authenticate 在 AuthService 类中存储状态.

At https://angular.io/docs/ts/latest/guide/router.html#!#teach-authguard-to-authenticate in AuthService class the state is stored.

是为了简化示例还是普遍做法?我知道服务被实例化并在它们声明的范围内存活,但这意味着我必须关心服务的提供位置才能知道状态持续多长时间.

Is it just to simplify the example or is it a common practice? I know that services are instantiated and live for the scope where they are declared, but that would mean that I would have to care where the service has been provided to know how long the state lasts.

推荐答案

让组件无状态并将状态存储在服务中通常是个好主意,尤其是在路由器添加的组件中,以便导航离开然后返回一条路线,不会丢弃数据.

It's usually a good idea to have components stateless and store the state in a service, especially in components added by the router, so that navigating away and later back to a route, doesn't drop the data.

因此对于您的问题:服务不应该是无状态的.它们通常是,但不是必需的.

Therefore to your question: Services are not supposed to be stateless. They often are, but it's not required.

您可以使用 NGRX Store 来存储状态,但这也是一项服务.

You can use an NGRX Store to store the state instead, but that's a service as well.

我必须关心服务是在哪里提供的,才能知道状态会持续多久.

I would have to care where the service has been provided to know how long the state lasts.

是的,这就是你必须做的.这通常很容易.如果您希望服务及其状态在整个应用程序生命周期内可用,则在 @NgModule() 中提供它(需要对延迟加载模块进行一些特殊处理),否则在组件中提供,服务的生命周期将随着组件实例被销毁而结束.

Yes, that's what you have to do. It's usually quite easy. If you want a service and its state to be available during the whole application lifetime, you provide it in @NgModule() (needs some special handling for lazy loaded modules), otherwise you provide it at a component, and the lifetime of the service will end with the component instance being destroyed.

这篇关于Angular2 的服务应该是无状态的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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