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

查看:61
本文介绍了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商店来存储状态,但这也是一项服务.

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天全站免登陆