Can you create a service in Angular without using a singleton pattern?

Good morning,

I understand that most people use Services in Angular as singletons to share the same instance of the service with other modules.

However, I have a specific need where I want each module that uses the service to create a new instance.

Let me explain further: I have a service called report-params-store-service that is designed to store data params for reports. I would like to inject this service into different types of reports such as INSS Reports, IRRF Reports, FGTS Reports, but I want each report to have its own isolated instance of the service without sharing data among them.

I want to avoid duplicating code by creating a separate instance of the report-params-store-service for each type of report.

Is this possible? And if so, how can I achieve it?

I tried putting the services in the providers section of each module, but it still behaves as a singleton service, sharing data across different modules.

Answer №1

To make changes in your service file, follow these steps:

Firstly, update the Injectable decorator from:

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

To:

@Injectable()

Subsequently, make sure to provide your service in each module like so:

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

Answer №2

For more information on how to limit the provider scope using lazy loading modules in Angular, refer to the detailed description in the official documentation: https://angular.io/guide/providers#limiting-provider-scope-by-lazy-loading-modules

When you set providedIn: 'any', eagerly loaded modules share a singleton instance, while lazy loaded modules have their own unique instances.

Make sure to set providedIn: 'any' for your service and add it to the providers array where necessary (in your module or standalone component).

Note that this concept only applies to lazy loaded modules, which is considered a best practice. If you are not utilizing them, consider referring to Khumo Mogorosi's answer for a more generic approach.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular 2 issue with nested form elements

Looking to build a form that includes nested sub/child components within it. Referring to this tutorial: https://scotch.io/tutorials/how-to-build-nested-model-driven-forms-in-angular-2 https://plnkr.co/edit/clTbNP7MHBbBbrUp20vr?p=info List of modificatio ...

Http' does not have the 'update' property

I recently implemented Angular 2 Release and utilized 'Http' from '@angular/http' for my project. However, I encountered an error when I invoked the method 'update', which resulted in the following message: "Evidently, th ...

Development of an Angular 4 application utilizing a bespoke HTML theme

I'm in the process of creating an Angular 4 project using Angular CLI and I need to incorporate a custom HTML theme. The theme includes CSS files, JS files, and font files. Where should I place all of these files? Should they go in the asset folder? O ...

Guide on making a fresh Angular component in JHipster

I recently developed a new project using jhipster and integrated it into Intellij. However, I encountered an error when attempting to create a new angular component. Here is the process I followed: File >> New >> Angular cli >> component ...

"During the constructor initialization, an Angular/TypeScript global variable that was assigned within an

Utilizing HTTP calls to my Web API to fetch 2 API keys for accessing another API. These API keys are fetched using 2 functions: getApiKey() and getAppId() Upon calling these functions within the constructor, the returned value, stored in a global variab ...

Using the spread operator in Typescript with an object that contains methods

Within my Angular project, I am faced with an object that includes a type and status field where the status can change depending on the type. While some might argue that this is not the best design practice, it is how things are currently structured in my ...

A guide to utilizing Angular 8 keyvalue alongside compareFn for intricate object comparison

Looking at this data structure: { "id": 1, "paragraphText": "I'm some Paragraph Text", "paragraphName": "new paragraph", "paragraphPlacement": { "id": 1, "order": 1 } } { "id": 1, "paragraphText": "I'm another Paragraph ...

Creating a dynamic text field integrated with Google Places in Ionic 4: a step-by-step guide

I am currently implementing the google-place-api autoComplete feature in my project, but I encountered an error: TypeError: Cannot read property 'getInputElement' of undefined .html <section [formGroupName]="i" *ngFor="l ...

Utilizing Bootstrap.css in various Angular modules

Is there a way to utilize bootstrap.css in specific modules rather than applying it to the entire application? I wish to avoid adding Bootstrap.css to index.html or styles of angular.json, and only use it in certain modules. In my project, I have two dis ...

What is the method for copying table data, including input text as cells, to the clipboard without using jQuery?

I have a basic table that looks like this: <table> <thead> <tr> <th>Savings</th> </tr> </thead> <tbody> <tr> <td>Savings <button type="button" (click)=" ...

Using RXJS with Typescript to wait for an observable to emit until another observable of type boolean evaluates to false

In my current setup, when a user navigates in a view, an API call is made to fetch the data for that specific view. This data is then used later on to decide whether a dialog should pop up when a user performs an action. While the solution is functional a ...

Angular - Implementing service worker to extract dynamic ID from route in "Notificationclick" event?

I have integrated push notifications into my code to notify users when an action is taken. The backend was developed using lib.net.webpush 3.1.0 with .net 4.5.2 in C#. The notification system is functioning well, but I am facing a challenge: Within my ser ...

Using Cypress.Promise in a Cypress command causes type conflicts

When using Cypress 8.x.x, the following Cypress command works fine: declare global { namespace Cypress { interface Chainable<Subject> { login(): Chainable<Token>; } } } Cypress.Commands.add('login', () => { ret ...

Exploring the method for obtaining parameters from a generic constructor

I have a customized class called Collection, which takes another class as a parameter named personClass. I expect the method add to accept parameters that are used in the constructor of the class User class Person { constructor(public data: object) { } ...

Factory function in Angular for translating using arrow syntax

When I include TranslateModule using the following code: TranslateModule.forRoot({ loader: { provide: TranslateLoader, useFactory: HttpLoaderFactory, deps: [HttpClient] } }) where export function HttpLoaderFactory(http: H ...

Encountering "No overload matches this call" error in Typescript while working with fetched data and material-ui

Before attempting to create a dropdown menu with an array retrieved using useSWR, I first practiced creating one with a hardcoded array. I used this for the initial practice: https://codesandbox.io/s/76k0ft?file=/demo.tsx:1819-2045 Instead of using a hard ...

A result of the array's elements' index will form an object

Here is a straightforward example for you to work with. I am trying to retrieve the index of each Test component. However, the key value is returning an object. Since I'm not very well-versed in Reactjs, could someone guide me on how to get the index ...

Sorting in an Angular mat table can be customized to consider two properties within a single

Trying to implement a table with MatSort, I've encountered an issue where every column sorts except for the third one: <ng-container matColumnDef="nbreEnregistrementTotal"> <th mat-header-cell *matHeaderCellDef mat-sort-header ...

Issue: anticipated ']' after statement in sanity in conjunction with nextjs

Struggling to retrieve data from Sanity in Next.js, but encountering an error that reads: "Error: expected ']' following expression." As a beginner in this, I've been trying to troubleshoot it, but I'm unsure of the root cause of the er ...

Troubleshooting Cross-Origin Resource Sharing issue between a Spring Boot backend and

I have attempted to establish a connection between a locally running Spring Boot application in VS Code and an Angular app in StackBlitz. However, I keep encountering the status "pending" followed by a net::error. Spring Boot version: 3.3.1 Angular versi ...