How to use useClass with Tree Shakable Services in Angular

Recently, I was asked that how can we use providers such as useClass inside a Tree Shakable service?   By default, Angular services are tree shakable, which means if the application does not use them, they are not part of the final bundle.

So, if you create a service using CLI as,

ng g s Log

Angular creates a service with provideIn option set to ‘root’ as shown below,


import { Injectable, Inject } from '@angular/core';
console.log("I am included in final bundle");

@Injectable({
  providedIn: 'root'
})
export class LogService {

  sayHello(name: string) {
    return "hello" + name;
  }
}

I have added a function SayHello() in the service, and by default, LogService is tree shakable and provided at the application level.

Another option to provide service at the application level is to pass it in the providers’ array of the AppModule.


 providers: [,         
    {provide:LogService,useClass:LogService}
  ],

The only difference here is that the service is no longer tree shakable. But you can configure the class to be used with the LogService token.

So now the question is how we can achieve,

  1. Tree shakable service
  2. And use useClass with that.

Angular provides a straightforward option to achieve it. You have to pass useClass as one of the other properties in the beside the provideIn property in the @Injectable decorator.


import { Injectable, Inject } from '@angular/core';
import { LogupdatedService } from './logupdated.service';
console.log("I am included in final bundle");

@Injectable({
  providedIn: 'root',
  useClass:LogupdatedService
})
export class LogService {

  sayHello(name: string) {
    return "hello" + name;
  }
}

Now the LogService is tree shakable and can is configured to use another class. I hope you find this post useful.  If you want to learn in detail about Angular Services and Dependency Injection, watch this ng-India webinar recording here:

Leave a comment

Create a website or blog at WordPress.com