Injecting multiple instances of an abstract service in Angular can be achieved using the following techniques

I am fairly new to Angular and currently trying to make sense of the code written by a more experienced developer. Please excuse me if I'm not adhering to the standard communication practices and vocabulary.

There is an abstract class called abstractDataService with an abstract method named getEntities(), which has two implementation classes: impl1 and impl2

The implementation class impl1 looks like this:

@Injectable()
export class impl1 extends abstractDatService{
  
  private entities: Modal[] = [
    {
      id: 1,
      type: "a",
      name: "a1"
    },
    {
      id: 2,
      type: "a",
      name: "a2"
    }
  ];

  public getEntities(): Observable<Modal[]> {
    return of(this.entities);
  }
}

Now, within my module, I'm attempting to inject the service as follows:

  providers: [
    {
      provide: abstractDatService,
      useClass: impl1
    },
    {
      provide: abstractDatService,
      useClass: impl2
    }
  ]

In this scenario, when I try to retrieve the entities, they are being returned only from the impl2 class and not from impl1

I would like the implementation to return both sets of data.

Is there anyone who can assist me in resolving this issue?

EDIT :

To further explain,

I have a component where I am presenting the data in the following manner:

HEAD1
Data from impl1 // this line represents a common component where data is displayed using ngFor on the observable returned.

HEAD2
Data from impl2 // this line signifies another common component where data is displayed using ngFor on the observable returned.

The common component is responsible for displaying the Data from impl1 and Data from impl2 together.

Answer №1

Based on the feedback given

Could you provide more details? When you say you want them both, are you referring to wanting the injected service to combine elements from both models when getEntities is called?

Yes, my goal is to have data from both impl1 and impl2 in the injected service.

There are two changes that need to be made.

1st: Update your provider definition to include multi: true

providers: [
    {
      provide: AbstractionService,
      useClass: Impl1Service,
      multi: true,
    },
    {
      provide: AbstractionService,
      useClass: Impl2Service,
      multi: true,
    }
  ]

2nd: Handle the multiple injections with an array

 constructor(@Inject(AbstractionService) impls: AbstractionService[]) {
    const obs$ = impls.map(impl => impl.getEntities());

    combineLatest(obs$).subscribe(console.log);
  }

You can find a working example on stackblitz here: https://stackblitz.com/edit/angular-ivy-pwysue?file=src/app/app.module.ts

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

Retrieving all rows from a table using Laravel API and Vue.js

<template> <div class="container"> <div class="row mt-5 mb-3"> <div class="col-md-10"> <h3>Gallery</h3> </div> <div class="col-md-2"> <button class="btn btn-success" ...

What makes CVE-2021-33623 susceptible to ReDoS attacks?

CVE-2021-33623 points out that the code snippet below (addressed in this commit, along with test cases) is susceptible to ReDoS vulnerabilities: trimNewlines.end = string => string.replace(/[\r\n]+$/, ''); What makes it prone to ReD ...

The function doc.fromHTML is not recognized in Angular 6

I am having trouble exporting an HTML template to a PDF using the jsPDF library with Angular. I keep getting the error message "doc.fromHTML is not a function." import { Component, ViewChild, ElementRef } from '@angular/core'; import * as jsPDF ...

Tips for creating unit tests for methods in Angular components with jasmine

As a beginner in jasmine unit testing, I am struggling to understand how to write and implement tests in jasmine. I have been encountering numerous errors along the way. Is there anyone who can assist me with writing a unit test for the code snippet below ...

mootools.floor dispose function malfunctioned

I am attempting to implement form validation with the following code: However, it does not seem to be working properly. <form name="niceform" id="third" action="" class="niceform" method="post" enctype="multipart/form-data"> <div class ...

What is the method to change lowercase and underscores to capitalize the letters and add spaces in ES6/React?

What is the best way to transform strings with underscores into spaces and convert them to proper case? CODE const string = sample_orders console.log(string.replace(/_/g, ' ')) Desired Result Sample Orders ...

What is the best way to position a tooltip near an element for optimal visibility?

One div is located on the page as follows: <div id="tip"> Text for tip goes here... </div> And another one can be found below: <div class="element"> Text for element goes here... </div> There is also a piece of JavaScript ...

Is there a way to reveal only the version information from the package.json file in an Angular 17 project?

Is there a secure way to extract and display only the version from a package.json file on the UI of a web application without exposing the rest of its contents? I am currently using the following structure in my package.json: { "name": "exa ...

iOS hover menu behavior: Close dropdown when the same element is tapped again on iPads

The navigation bar features categories such as: politics, economy, education Upon clicking on these categories, a dropdown menu appears with locations like: asia, europe, North America What I am looking for is this: If the user clicks (tabs) or hovers (o ...

In Discord.js, the client.login() promise seems to be stuck and never resolves, causing the client.on("ready") event to never be

After creating a simple Discord bot using discord.js, I programmed it to respond with the message "Good morning to you too" whenever someone sends a message containing "good morning". Surprisingly, this feature worked seamlessly until recently when the bot ...

Is it permissible to make alterations to npm modules for node.js and then share them publicly?

I have made modifications to a module called scribe.js that I use in my own module, which is published on npm. Instead of using the original module as a dependency for my module, I would like to include my modified version. I am unsure about the legal impl ...

How can a controller in AngularJS detect when the back button of the browser is pressed

I've created a browser trivia game where authenticated players can select a game type, triggering a socket.io event in my Node.js server. The view then transitions to a "Searching for game" screen with a loading icon as the server waits for enough pla ...

Autocomplete feature in MUI allows filtering to begin after typing at least 3 characters

I've encountered an issue with the Autocomplete MUI component I'm using to filter a list of checkboxes. The popup with options should remain open at all times, but I only want the filtering to be triggered when the user input is more than 3 chara ...

What is the method to verify if a pop-up browser window has completed its loading process?

There is a link on my website that opens a new window. However, sometimes the new window takes so long to load. To prevent users from clicking on the link before the new window finishes loading, I want to disable it until then. I am aware that one way to ...

Ensure that the first option in the Woocommerce 2 Variable Product Dropdown List always displays all available choices

I am currently working on a variable WooCommerce product that includes 2 drop-down select fields. The first field is for selecting the Type of Product (framed or unframed artwork) and the second field is for choosing the Size of Artwork. With the help of ...

Using JSTL within JavaScript

Can JavaScript be used with JSTL? I am attempting to set <c:set var="abc" value="yes"/> and then later retrieve this value in HTML and execute some code. The issue I'm facing is that the c:set always executes even when the JavaScript condition ...

Incorporating AJAX functionality into an existing PHP form

I am currently working on a PHP registration form that validates user inputs using $_POST[] requests. Validating username length (3-20 characters) Checking username availability Ensuring the username matches /^[A-Za-z0-9_]+$/ pattern and more... Instead ...

What is the best way to define a variable within a function?

Here's a function designed to verify if the username has admin privileges: module.exports = { checkAdmin: function(username){ var _this = this; var admin = null; sql.execute(sql.format('SELECT * FROM tbl_admins'), (err, result, fields ...

Display a video modal upon page load, allowing users the option to click a button to reopen the modal

Looking for a way to make a video modal automatically open on page load and allow users to reopen it by clicking a button? Here's a snippet of code that might help you achieve that: HTML <html> <head> <link rel="stylesheet ...

refetchQueries may be effective for specific queries

Using a Friend component within my AllFriends screen triggers the following mutation: const [deleteUserRelation] = useDeleteUserRelationMutation({ onCompleted: () => { Alert.alert('Unfriended'); }, refetchQueries: [{ query: ...