Wednesday, 18 April, 2018 UTC


Summary

  • Angular Services do NOT have to be Singletons – As you probably know, when we add a service to a @NgModule() declaration, it will be a Singelton.
  • For example: – export class AdminService { – data = providers: [AdminService, AdminDataService] – })I see a lot of people whose first instinct is to just put all their services in @NgModule() declarations without thinking about the consequences.
  • The sole purpose of the service is to share data between child’s components and to provide a couple of helper’s methods.
  • So, we just stick it in the component providers and make it a non-singleton service.
  • @Component({ – selector: ‘admin-tab’, – providers: [AdminService, AdminDataService] – })The benefit is that when Angular destroyed the component, she will also destroy the service and release the memory that is occupied by him.
As you probably know, when we add a service to a @NgModule() declaration, it will be a Singelton. Meaning, it will live as long as our application lives. For example: I see a lot of people whose…
@NetanelBasal: I just published “Angular Services do NOT have to be Singletons”
Angular Services do NOT have to be Singletons
As you probably know, when we add a service to a @NgModule() declaration, it will be a Singelton. Meaning, it will live as long as our application lives. For example:
export class AdminService {
data = providers: [AdminService, AdminDataService]
})I see a lot of people whose first instinct is to just put all their services in @NgModule() declarations without thinking about the consequences.
You are not releasing memoryAlthough you probably do not need this memory anymore. Let’s stop for a second and think, do we really need this service to be a wide app singleton?
For example, in our application, we have an admin section where we need to display a big list of data which, of course, is stored in memory.
We don’t need this service to be a singleton. We don’t need a caching layer and no one out of this tab needs data from it.
The sole purpose of the service is to share data between child’s components and to provide a couple of helper’s methods.
So, we just stick it in the component providers and make it a non-singleton service.
@Component({
selector: ‘admin-tab’,
providers: [AdminService, AdminDataService]
})The benefit is that when Angular destroyed the component, she will also destroy the service and release the memory that is occupied by him.
Angular Services do NOT have to be Singletons – Netanel Basal