Angular: Utilizing multiple instances of a single service

The Issue

In my Angular application, I am using a third-party module service that handles REST calls to the backend. This service is utilized in two separate components, but conflicts can arise when both components make requests simultaneously due to the asynchronous nature of the REST calls.

To illustrate, here is a simplified version of the third party service:

@Injectable({
    providedIn: 'root'
})
export class ThirdPartyService {

  dataLoaded: Subject<Result> = new Subject();

  callBackend(request: RequestBody): Observable<Result> {
    const promise = this.someJSLibrary.call(request);

    promise.then((result: Result) => {
      this.dataLoaded.next(result);
    });

    return from(promise);
  }
}

When both components call callBackend() at the same time, their results may overwrite each other in the dataLoaded field.

The Query

How can this conflicting behavior be prevented? Is there a way to create multiple instances of the service and restrict their scope to individual components?

I have come across suggestions on StackOverflow recommending the use of custom factory functions to address this issue. Is this the most effective solution for tackling such a common problem?

Answer №1

I stumbled upon the solution while browsing through the Angular documentation. I wanted to share it here in case it can assist someone else in the future.

Basically, to restrict the scope of a service to a component, you need to add it to the provider array within the @Component decorator:

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.scss'],
  providers: [ ThirdPartyService ]  // <--- this is the key
})
export class MyComponent {
  // ...
}

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

Is there a way to retrieve the zoom level in Highmaps and are there any events related to zooming in Highmaps

Is there a way to trigger a zoom event in Highmaps? Furthermore, how can the current zoom level of the map be retrieved? Adjusting the zoom level is straightforward, but extracting it proves to be more challenging. After exploring the API documentation, ...

Error message during ng Build Prod: Component declared in two modules when it should be in the same module

When running the ng build --prod command, I encountered an error message that is causing some confusion: The error states: Type SiteSecurity in "PATH"/siteSecurity.component.ts belongs to the declarations of 2 modules: SiteSecurityModule in "PATH"/s ...

Ways to activate button only when an item is chosen from the dropdown menu

I'm working on an Angular 8 application that utilizes Angular Material. I have multiple dropdown lists with a button that triggers a function based on the selected values from the dropdowns. Initially, when the page loads, the button is disabled. How ...

How can I properly display each option of a ngx-bootstrap-multiselect on a separate row?

After upgrading my Angular 8 project to Angular 9, I decided to experiment with the ngx-bootstrap-multiselect plugin. I noticed that the way the items are displayed on a single line is causing some display issues, such as checkboxes appearing to the right ...

Dexie is alerting us to a problem with a call that occurs before initialization

When setting up my application, I encountered an error related to the Courses Entity Class being called before initialization in my Dexie Database. Despite checking my code, I couldn't find any issues and there was no documentation available for this ...

issue with sending http requests using ionic2/3

I'm still relatively new to using ionic2, even though I have some experience with programming in general. Currently, I'm experimenting with ionic2 and attempting to send simple get/post requests to my locally hosted web services for development p ...

Issue with sending files to web API using Angular FormData

After stepping through the code, I noticed that my formData is empty when it reaches the API side, with the parameter pFileToUpload having a value of null. Step 1: HTML <div class="form-group"> <input type="file" id="f ...

Discover unutilized attributes within a destructured parameter object in Typescript

We are interested in identifying unused properties within destructured parameters in Typescript using tools like ESlint or TypeScript. For example, we want to detect the unused property "c" in the following code: const myIncompletelyRefactoredFunction = ( ...

Unit testing the error function within the subscribe method in Angular

I've been working on a unit test for the subscribe call, but I'm struggling to cover the error handling aspect of the subscribe method. The handleError function deals with statusCode=403 errors and other status codes. Any assistance would be grea ...

Unable to classify mapRef.current

I am facing an issue with my react component that contains a leaflet map. TypeScript is warning me about line mapRef.current.setView(coords, 13), stating it is an "unsafe call of an any typed value" import 'leaflet/dist/leaflet.css'; import { Map ...

What causes TypeScript to generate an error when using two array of object types, but not when using the shape of both?

There are two basic types of data available: type DataA = { percent: string; exchange: string; }; type DataB = { price: number; exchange: string; }; I'm puzzled as to why TypeScript gives errors when I try to use both types together: const ...

When running the command `npm start`, an error message is generated

Hey everyone, I've been trying to learn some basic AngularJS 2.0 skills through a tutorial. Unfortunately, when I tried running the command npm run start, it didn't work as expected. I'm currently using Git Bash on Windows 10 OS. If you hav ...

Safari Mobile users are still experiencing popup prompts even after disabling the block popup setting

I am experiencing an issue with my Safari browser on iPhone 11. Despite having the "block popups" setting turned off, I keep receiving a popup message when using the following line of angular code: This site is attempting to open pop-up window When I cli ...

Steps to create an Executable from a complete Typescript project

My current project in Typescript consists of multiple folders and config files that are interconnected to form a larger script. I am looking for the best approach to compile it into an executable. Key points to consider: • Multiple Typescript files w ...

Passing HttpClient from app.module to another module and then to a service in Angular

Currently, I am in the process of developing my own Angular NPM Package with the prefix "ngx-*". I have successfully compiled the package and am now integrating it into a new project by utilizing the npm link command. Within the service, there is a constr ...

Tips for correctly annotating objects to address the issue of potentially being 'null'

Could use some assistance with this error: Object is possibly 'null' on this.auth.currentUser. How should I annotate this line to resolve the issue? Here's the method in question: doPasswordUpdate = (password: string): Promise<void> ...

Struggling with getting Angular 2 npm start to function properly, as it keeps returning Exit status

I am facing an issue with my angular 2 application on my laptop. It works fine for me, but when my teammate tries to clone it using git, he encounters a strange error when running npm start. He has node.js installed and the files are exactly the same. He ...

Assign a value of 0 to the ngModel if it is empty

I am trying to ensure that when the value is null, it defaults to 0. At the moment, I am utilizing Angular PrimeNG components. <p-calendar [(ngModel)]="model.start_time" [timeOnly]="true" placeholder="00:00"></p-calen ...

Can Primeng and Angular2 be integrated into JSF without the use of npm?

I'm looking to implement the Angular2 framework for my frontend development, and I've decided to use PrimeNG for the UI components. However, I am not familiar with how npm functions. Here are some tech details: I will be using Eclipse or NetBe ...

Guide on inserting Angular 2 attributes within a variable in an Angular 2 TypeScript class

I have a variable 'content' in the 'findCharityHome.ts' typescript class structured like this. let content = ` <b>`+header+`</b> <button style='background-color:#428bca;color:white; ...