How can you create a transient service in Angular?

  • When you register a service into DI in Angular, the services are marked Singleton.
  • Alternatively to create a transient service (a new instance of service is returned from DI whenever requested), we can use factory while declaring in the NgModule.
  • To register a service of type Engine as a transient, whose constructor requires two dependencies of type Dep1 and Dep2 we do it as below:
{
  provide: Engine,
  useFactory: (arg1: Dep1, arg2: Dep2) {
    return () => {
      return new Engine();
    }
  },
  deps: [Dep1, Dep2]
}
  • When you register a service into DI in Angular, the services are marked Singleton.
  • Alternatively to create a transient service (a new instance of service is returned from DI whenever requested), we can use factory while declaring in the NgModule.
  • To register a service of type Engine as a transient, whose constructor requires two dependencies of type Dep1 and Dep2 we do it as below:
{
  provide: Engine,
  useFactory: (arg1: Dep1, arg2: Dep2) {
    return () => {
      return new Engine();
    }
  },
  deps: [Dep1, Dep2]
}
Default image
Sriram Mannava

I'm a full-stack developer and a software enthusiast who likes to play around with cloud and tech stack out of curiosity.

Leave a Reply