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

Privacy Overview
Referbruv

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

Strictly Necessary Cookies

Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.

3rd Party Cookies

This website uses Google Analytics to collect anonymous information such as the number of visitors to the site, and the most popular pages.

Keeping this cookie enabled helps us to improve our website.