As you probably know, when we add a service to a @NgModule() declaration, it will be a Singleton. Meaning, it will live as long as our application lives. For example:

export class AdminService {

data = Array(10000).fill(dummy);

} @NgModule({

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 problem with that is:

You are not releasing memory

Although you probably don’t need this memory anymore. Let’s stop for a second and think, do we really need this service to be an 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 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 it.

OnDestroy Hook

Many developers don’t know this, but non-singletons services also have the ngOnDestroy() lifecycle hook. You can use it for cleaning.

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. Thanks to Alexey Zuev for the comment.

Follow me on Medium or Twitter to read more about Angular, Vue and JS!

👂🏻 Last but Not Least, Have you Heard of Akita?

Akita is a state management pattern that we’ve developed here in Datorama. It’s been successfully used in a big data production environment for over seven months, and we’re continually adding features to it.

Akita encourages simplicity. It saves you the hassle of creating boilerplate code and offers powerful tools with a moderate learning curve, suitable for both experienced and inexperienced developers alike.

I highly recommend checking it out.