A single element containing two duplicates of identical services

I am encountering an issue with my query builder service in a component where I need to use it twice. Despite trying to inject the service twice, it seems that they just reference each other instead of functioning independently, as shown below:

@Component({
  selector: 'app-manage-users',
  templateUrl: './manage-users.component.html',
  styleUrls: ['./manage-users.component.scss'],
  providers: [UserManagementQueryBuilderProvider]
})
export class ManageUsersComponent implements OnInit {

  public constructor(
    private readonly queryBuilder: QueryBuilderService,
    private readonly qb: QueryBuilderService
  ) { }

  public ngOnInit() {
    this.queryBuilder.table('users');
    console.log(this.qb['_table']); // Outputs "users"; expecting an empty string.
  }
}

It is uncertain whether this issue stems from the way my provider is configured (specifically the multi option), but here is how it is set up:

export const UserManagementQueryBuilderProvider: Provider = {
  useFactory: (httpClient: HttpClient) => new QueryBuilderService(httpClient)
    .connection(environment.USER_MANAGEMENT_API),
  provide: QueryBuilderService,
  deps: [HttpClient],
  multi: false
};

When I change multi to true, I encounter an error stating that "table" is not a function.

ERROR Error: Uncaught (in promise): TypeError: this.queryBuilder.table is not a function

The structure of the QueryBuilderService is as follows:

@Injectable({ providedIn: 'root' })
export abstract class GraphQLClientService {
  public constructor(
    private readonly httpClient: HttpClient
  ) { }
}


@Injectable()
export class QueryBuilderService extends GraphQLClientService { }

Answer №1

Alias providers:
The useExisting provider key allows you to create an alias for a service by mapping one token to another. This means that the first token serves as an alias for the service associated with the second token, providing two ways to access the same service object. (Angular Docs)

To illustrate, consider using two InjectionTokens with UseExisting set to false. This approach will result in two distinct instances of QueryBuilderService being injected, as shown in the example below:

import { Component, InjectionToken, Inject } from '@angular/core';

const QueryBuilder1 = new InjectionToken("QB1");
const QueryBuilder2 = new InjectionToken("QB2");

@Component({
  providers: [
    {
      provide: QueryBuilder1,
      useClass: QueryBuilderService,
      useExisting: false
    },
    {
      provide: QueryBuilder2,
      useClass: QueryBuilderService,
      useExisting: false
    }
  ]
})
export class ManageUsersComponent {

  public constructor(
    @Inject(QueryBuilder1) private queryBuilder1: QueryBuilderService,
    @Inject(QueryBuilder2) private queryBuilder2: QueryBuilderService
  ) { }

}

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

Disable the background color css when hovering over a button

I'm having trouble with my Angular and HTML code. https://i.stack.imgur.com/Ea5oV.png The image above shows that a background color appears when hovering over the first icon. I've attempted: .sidemenuitm { padding: 10px 5px; cursor: poin ...

Using Angular Ionic for a click event that is triggered by a specific class

I am utilizing Highcharts and would like to click on the legend upon loading. With the use of Angular Ionic, how can I trigger a click on the .highcharts-legend-item class within the ngOnInit() {} method? I am aiming to click on this class as soon as the ...

Is there a method to have JavaScript display all the information during a SQL while loop?

I'm currently working on implementing a timer for my script. However, I am facing an issue where the timer only counts down from the last result instead of each individual result returned from the query. Any assistance with resolving this problem woul ...

Anyone have any (placeholder) fetch URL parameters that require some time to resolve?

Can anyone share any fetch URL parameters that result in a loading time of roughly 5 seconds or longer for the promise to resolve when using fetch(urlArgument);? I'm eager to experiment and learn more. ...

Using JavaScript to place markers on a Google Map may encounter an issue with a for

Close to solving a three-day challenge. Currently working on placing markers on a Google Map using latitudes and longitudes stored in a Django model. This is my first time using AJAX, but I'm giving it a shot to make this work. Firebug is pointing out ...

Utilizing Jquery or Javascript to Establish a Fresh Perspective for CylinderGeometry with Three.js

I'm attempting to change the dimensions of a cylinder created using examples from Three.js at runtime, but my code doesn't seem to be working. Here is the code snippet I am using: HTML <script src="http://www.html5canvastutorials.com/librari ...

Using jQuery to compel a user to choose a value from the autocomplete suggestions within a textarea

Currently, I have implemented a snippet that allows the user to choose cities from a list and insert them into a textarea separated by commas. However, I am looking to enhance this feature. I want the user to be able to search for a city by typing a part ...

Show the template when the link is clicked using Angular directive

Perhaps the question is not phrased properly, but here is the idea I am working on. I have a navbar set up with an array of countries that includes their names and coordinates. <body> <nav class="navbar navbar-default"> <div cl ...

The value of a checkbox in Angular 10 is coming out as undefined

Within my component, I set up the formGroup as shown below: constructor(private apiService: ApiService) { this.form = new FormGroup({ product: new FormControl(), shops: new FormGroup({}) }); } When selecting a vendor from a drop-do ...

Using async method in controller with NestJS Interceptor

I am seeking a way to capture both the result and any potential errors from an asynchronous method within a controller using an interceptor. When an error is thrown, the interceptor can respond accordingly. However, I am struggling to figure out how to tri ...

Utilize React to process and submit payments through Stripe

I am currently working on integrating Stripe Elements with my React application. The JavaScript page below showcases the code I use to submit the payment form, which I have compiled from various sources online. Upon submitting the form, I receive a token; ...

Sending a parameter to a form within Edge Animate

I'm facing an issue where I need to pass a variable to a form from Edge Animate. Here's the current instruction snippet: sym.$("form").append('<iframe width="100%" height="100%" src="login_PRA.php?v_id="vidn frameborder="0" scrolling="no ...

Should I reload the entire table or insert a row manually?

This unique ajax question arises: within a table lies the users' information, displayed based on individual settings and timing. Sometimes, users instantly see the data, other times they must wait for it - their choice determines when it appears. Wha ...

Issue: "StoreController Undefined" error in Python Flask + Angular application

In the python flask application that I have built with Angular JS for the front end, there are three main files. app.py import json import flask import numpy as np app = flask.Flask(__name__) @app.route("/") def index(): ...

JavaScript - incorrect order for compiling

Is the user already in my SQLite database? If the user exists: return 500 (ERROR!!) If the user does not exist: return 200 (OK) This is my Node.js + Express script running on the server side. app.post('/adduser', function(req, res){ db.se ...

JS/Apps Script: Passing object and its keys as function parameters

When working with Google Apps Script, I have a specific task that involves looping through data and writing only certain keys to a sheet. I want this looping operation to be done in a separate function rather than directly in the main function, as it will ...

What is the most effective method for generating dial images through programming?

Currently, I am in the process of creating a website that makes use of variously sized and styled dials to indicate progress. The filled portion of the dial represents how close an item is to being 100% complete. I am seeking a universal solution that wil ...

Continuously encountering CORS errors despite activating them, using .NET Core in conjunction with an Angular client

I recently encountered a CORS issue in my .NET Core 3.0 Web API project despite having enabled CORS in the startup file. Here's how I configured it: ConfigureService services.AddCors(options => { options.AddPolicy("AllowOrigin", builder => b ...

An error popped up as I attempted to load an existing design within the vue-email-editor

https://i.stack.imgur.com/0ObU5.png Check out the code snippet below for the function I have created: editorLoaded() { this.$refs.emailEditor.editor.loadDesign(this.emailJson); console.log('editorLoaded'); }, ...

The TypeScript compiler is unable to locate the module react-scripts within the lerna webpack configuration

Recently, I've been working on setting up a new project using lerna, react-scripts, webpack, and sass. Here is my current directory structure: myApp /packages /myReactApp -> a react create app application /tsconfig.json /package ...