Are Angular2's services supposed to be stateless?

后端 未结 1 1631
耶瑟儿~
耶瑟儿~ 2021-01-04 04:27

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

相关标签:
1条回答
  • 2021-01-04 04:59

    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.

    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.

    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.

    0 讨论(0)
提交回复
热议问题