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

Angular Posted Feb 22, 2021

Join the Newsletter

Subscribe to get our latest content by email.
    We won't send you spam. Unsubscribe at any time.
    We use cookies to provide you with a great user experience, analyze traffic and serve targeted promotions.   Learn More   Accept