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

Javascript retrieve the style of an element in every possible state

I am interested in retrieving the line height of an element; it's a simple task. Here is a method that I know works: console.log(document.getElementById("myDiv").style.lineHeight); console.log($("#myDiv").css('lineHeight')) ...

What is the method to access 'let' variables in the console of a developer tool?

When you open the Chrome devtool and enter the code snippet below: // The iife is irrelevant let r = (() => { return 2; })(); and then evaluate r, the output will be: r 2 Surprisingly, both window.r and globalThis.r return undefined. Although let is ...

Setting the default value in setState in React Native allows you to initialize state

const fetchData = async (key) => { try { const jsonData = await AsyncStorage.getItem(key) return jsonData != null ? JSON.parse(jsonData) : false; } catch(error) { console.log(error); } } useEffect ...

Using VueJS to determine if a certain string includes a specific substring within an if-statement embedded within a v

I am aiming to verify if the link in a json object contains 'http'. If it does, I want to assign a target='_blank' attribute to the v-btn. The link could also be something like #test. Currently, this is how I am attempting to achieve i ...

A guide to querying JSON data in a backend database with JavaScript

My backend JSON DB is hosted on http://localhost:3000/user and contains the following data: db.json { "user": [ { "id": 1, "name": "Stephen", "profile": "[Unsplash URL Placehol ...

Is there a way to prevent tags from wrapping and showcase them all in a single line when utilizing the jQuery select2 plugin?

I have a requirement to prevent tags from wrapping and instead display them in a single line using the jQuery TagIt plugin. Check out my preview: https://i.stack.imgur.com/lYhsi.png My goal is to have all the tags displayed on a single line without wra ...

Number input in JavaScript being disrupted by stray commas

On my webpage, there are elements that users can control. One of these is a text input field for numbers. When users enter digits like 9000, everything functions correctly. However, if they use comma notation such as 9,000, JavaScript doesn't recogniz ...

What is the best way to choose the checked items and calculate the total price by adding up all the prices of the selected items?

Seeking help with utilizing JavaScript to identify and collect all checked items from an HTML file. I'm looking to determine which items have been selected from a menu, each of which has an associated price. How can I access the prices of the chec ...

Setting up proxy middleware in an express application

My application is structured with a frontend server (React) serving static files and a backend server (Express). I have noticed that custom header requests trigger preflight requests, causing latency in my application. My goal is to eliminate these preflig ...

Can media queries styles be applied to a window of random size using JavaScript?

Can JavaScript be used to apply media queries style based on random window sizes? I have 5 buttons that I want to switch styles for using JavaScript according to the media queries defined in my CSS stylesheet. Is there a method to achieve this? ...

Discover past stock prices on Yahoo Finance

I'm stuck on tweaking a functioning jfiddle example that I have. Can anyone help me with this two-part question regarding the jfiddle: http://jsfiddle.net/maxmillien/qPVSy/ Part 1) Is there a way to clear the search each time a new search is performe ...

jQuery function to automatically close any other opened divs when a new div is opened

I have multiple elements that reveal a div when clicked. The issue is that if all elements are clicked, all divs open instead of just the one that was clicked. This is my jQuery code: <script> $(document).ready(function() { $('.servicemark ...

Having trouble with ReactJS rendering components?

FriendList.js var React = require('react'); var Friend = require('./friend.js'); var FriendList = React.createClass({ render: function() { return( <div> <h3& ...

Tips for displaying my libraries' function arguments while hovering in VSCode

As the creator of a JavaScript library, I am intrigued by how some libraries display function parameters and definitions when hovering over them in VSCode. Despite my efforts to add jsdoc style comments around the class definitions, I have not been able to ...

Ways to extract a value from an HTML form in ASP.NET when using Html.EnumDropDownListFor

I am a beginner in ASP.NET and I recently set up a form that allows input from a C# enum: <form method="get"> <div class="form-group"> <label>Select Type:</label> @Html.EnumDropDownListFor(x = ...

Error message encountered: ReferenceError - The subcommand specified in Discord.js Slash Command function is undefined

I have been experimenting with subcommands in a slash command for a discord bot. I plan to have several similar subcommands, so I wanted to create a function that can be called within .addSubCommand, but it seems like it's not functioning correctly. ...

Error: The hook call is invalid and can only be made within the body of a function component in ReactJS

Hello everyone, I am currently facing an issue with saving the lat and lng variables in the state within a hook. When trying to do so, I encounter the following error message: "Error: Invalid hook call. Hooks can only be called inside the body of a functio ...

What steps can I take to resolve the Angular JS error message: [$injector:unpr]?

index.html <!DOCTYPE html> <html lang="en" ng-app="myApp"> <head> <meta charset="UTF-8"> <title>Angular JS</title> <script src="lib/angular.min.js"></script> ...

Tips for incorporating the Sanitize library into Angular 6:

What is the most effective library for sanitization in Angular 6 to enhance security measures? Since injecting dependencies can be tricky, what are some recommended methods for implementing this in an Angular 6 project? ...

Mastering the art of debugging a mongoose action in node.js

I am utilizing mongoose for connecting my node.js app with mongoDB. However, I am facing an issue where the database does not get updated when I create or update a model instance. How can I effectively debug and identify what goes wrong in the create or up ...