Search code examples
angulartypescriptservicesingleton

Is it possible make a service in angular without singleton?


Morning,

I know that most use of Services in Angular is as singleton, to be able to share the same instance of the service with others modules.

However, I have a need in which I want each module that I provide the service in the section Providers be a new instance.

I explain: I have the services report-params-store-service that was created to save data params of reports. So I would like of injecting the report-params-store-service in, for example, INSS Reports, IRRF Reports, FGTS Reports, but that in each one of them was a isolated service, without singleton, because I am not wanna share datas params among the different reports that was injected by the same service report-params-store-service.

I am only wanna avoid repeating line code of the report-params-store-service having that to create one of him for each reports that I have.

Is it possible ? And how ?

I put the services in the providers in the each module that I needed but It behaved as a singleton service, sharing the data among the different modules.


Solution

  • In your service file change the following:

    From:

    @Injectable({
       providedIn: 'root',
    })
    

    To:

    @Injectable()
    

    Then provide your service in every module like this:

    @NgModule({
      declarations: [...],
      imports: [...],
      providers: [ReportParamsStoreService ],
    })
    export class FeatureModule {}