Sharing Top Content from the Angular-sphere.

Angular Services do NOT have to be Singletons – Netanel Basal

Angular Services do NOT have to be Singletons  #angular #singletons #typescript

  • 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, Angular will also destroy the service and release the memory that is occupied by him.
  • export class AdminService implements OnDestroy { ngOnDestroy() { – // Clean subscriptions, intervals, etc – } – }Also if we call NgModuleRef.destroy() or PlatformRef.destroy() then ngOnDestroy method of singleton providers will be also executed.

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…

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, Angular will also destroy the service and release the memory that is occupied by him.

OnDestroy HookMany developers do not know this but non-singletons services…

Angular Services do NOT have to be Singletons – Netanel Basal