How can you create a transient service in Angular?

When you register a service into DI in Angular, the services are marked Singleton

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]
}

Buy Me A Coffee

Found this article helpful? Please consider supporting!

Ram
Ram

I'm a full-stack developer and a software enthusiast who likes to play around with cloud and tech stack out of curiosity. You can connect with me on Medium, Twitter or LinkedIn.

Leave a Reply

Your email address will not be published. Required fields are marked *