Leveraging existing providers in Angular 2

What are the possible uses for the useExisting provider?

Is it more akin to useExistingOrThrowIfThereIsNone or useExistingOrCreateIfThereIsNone? Is there a way to intentionally choose between these behaviors depending on our specific requirements? If one of these options is not supported, can we somehow mimic its functionality?

The documentation lacks clarity on this topic and only provides an example where the useExisting provider reuses an instance from a useClass.

Answer №1

Consider this scenario

providers: [
    X, 
    {provide: Y, useClass: X}, 
    {provide: Z, useExisting: X}]

If you declare

constructor(private x: X)

a new instance for the first provider will be generated.

constructor(private y: Y)

a new instance for the second provider will be created

constructor(private z: Z)

the existing instance of the first provider is utilized.

When you initialize with

constructor(private z: Z)

a fresh instance for the first provider is produced and utilized

Answer №2

Adding some clarity to @GünterZöchbauer's response.

When dealing with tokens, useExistingOrThrowIfThereIsNone is the correct term. useExisting simply creates an alias for another token, not an instance. Therefore, there must be a token referenced by useExisting, or else an exception will be thrown. However, when it comes to instances, it will function as long as the last token in the chain registers an instance, making it effectively useExistingOrCreateIfThereIsNone.

For example:

// T = token, I = instance
providers: [
    {provide: B, useClass: A}, // T[B] => I[A]
    {provide: C, useExisting: A}] // T[C] => ??? - there's no T[A] declared

...
constructor(private a: B) {} // works
...
constructor(private a: C) {} // throws an exception: 

In this scenario, the second declaration will throw an error because token C refers to token A, which is not declared anywhere, even if there is an instance of class A in the injector. Angular will not automatically create an instance A for token C or associate token C with an existing instance A. This was accidentally discovered in one of my projects. :)

The following example will work due to the reasons explained in other responses:

providers: [
    {provide: B, useClass: A}, // T[B] => I[A]
    {provide: C, useExisting: B}] // T[C] => T[B] => I[A]

...

constructor(private a: B) {} // works
...
constructor(private a: C) {} // works

In this case, an instance of A will be created for token C, even if no instance of A was previously created for token B. Therefore, for token C, it means "use whatever instance should be provided for token B", and for token B, it means "use existing instance A or create new if none exists".

Answer №3

When we specify {provide: X, useClass: Y}, Angular will establish a connection between the keyword X and the definition Y.

If we use {provide: X, useExisting: Y}, Angular will link the identifier X with the identifier Y.

Here is how these connections differ:

  • Identifier X points to an instance of definition Y.
  • Identifier X points to identifier Y which in turn points to an instance of a certain definition associated with identifier Y.

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

Tips for holding down a non-modifier key, like the space key, with selenium as a user

I encountered an issue where selenium is unable to press and hold a key that is not included in the list of predefined keys: Keys.SHIFT, Keys.CONTROL, Keys.ALT, Keys.META, Keys.COMMAND, Keys.LEFT_ALT, Keys.LEFT_CONTROL, Keys.LEFT_SHIFT In my application, ...

The isolated scope member is being updated within the link/controller function, but it becomes undefined when passed to the controller

In the code snippet below: HTML: <body ng-controller="MainCtrl"> <main-dir data="data" on-update-map="updateMap(datalength)"></main-dir> </body> JS: app.directive('mainDir', function () { function DatasetDirect ...

Encountering a Schema error when using Components in an Angular 7 Element

I have been working on integrating various external libraries into my custom component to use in a dashboard project I'm developing. To simplify the process, I decided to create an Angular Element that includes a Line Chart, Graphic Gauge, and additio ...

The readyState remains stuck at 1 without progressing further

Struggling to input data into an XML using javascript's open() function. The website remains stuck at readyState 1, Here is the Javascript code snippet: function addItem() { var name = document.getElementById('Iname').value; va ...

Steps to keep only one submenu open at a time and close others

Struggling to figure out how to open one submenu at a time, and I can't seem to locate the issue! I've searched around for solutions but haven't found anything that works for me. The submenu also needs to remain closed when the page loads. - ...

I'm encountering an issue with the React state where it seems to be endlessly nesting

I am new to React and I seem to be encountering an issue where every time I trigger a click event, the state object continues to nest. The code snippet below is part of the App component. const [state, setstate] = useState('') useEffect(() =& ...

The jquery function is not operating as anticipated

I wrote the following code to toggle a class for a div. <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <html> <head> </head> <body> <div class="members-section " id="a ...

The callbacks for the SignalR JavaScript Client are failing to trigger

Despite successfully connecting to my Hub and setting up the OnConnected and OnDisconnected functions to update an integer value and trigger a client callback with the new value, I am facing an issue in my angular application where the registered callback ...

Steps to include a catch statement to resolve Unhandled promise rejection alert

I am currently working on implementing user authentication for my website. The registration route is functioning perfectly, but I seem to encounter an Unhandled promise rejection warning when attempting to make a request to the login route. I have attempt ...

Guide to dynamically adding two CSS files in a single component in Angular 8

Within this component, there is a form that needs to support two languages, each with its own unique CSS style - one for left-to-right (ltr) direction, and the other for right-to-left (rtl) direction. Is there a way to conditionally apply two different CS ...

Unique ways to serialize an HTML element efficiently: JavaScript tricks

Is there a way to store a reference of an HTML tag for future use? For instance, if I click on a div and save a pointer to that div in JavaScript, is it possible to serialize this pointer and then de-serialize it to use in another part of the web applicat ...

Is there a way to detect a class change using jQuery?

Below is an example of a div: <div id="components-reconnect-modal" class="components-connecting-show"> <div id="1"> <div id="2"> <div id="3"> <div id="4"> </div> The ID will remain constant, but the class will ...

After clicking, the React mobile navigation fails to collapse

At a certain breakpoint, my mobile navigation bar appears with a MENU button. When the MENU button is clicked, the menu opens and the button changes to CLOSE. Clicking on CLOSE collapses the menu, returning the button to MENU. However, when I click on th ...

In Angular 8, a communication service facilitates interaction between parents and children

Using a Sharing service, I am able to pass data from my app component to the router-outlet render component. While I have been successful in passing strings and other data, I am now looking for a way to retrieve data from an API and share it with a compone ...

Is it possible for me to dictate the sequence in which javascript / jQuery events are triggered?

Issue at Hand In my asp.net webform, I have a grid where users can update textboxes. These updates trigger a WebMethod call, updating the rest of the row without saving. To save the changes, users must click a save button. While this system works well in ...

Tips for utilizing Sass and CSS Modules within create-react-app

I've been using FileName.module.scss to style my react elements like this: // Component styling with SCSS import React from "react"; import Aux from '../../hoc/Aux'; import classes from './Layout.module.scss'; const lay ...

To achieve the desired format, where should I press or manipulate the information?

I need help with manipulating arrays to generate a specific JSON file structure. I've made some progress but got stuck at this point: var T_nn_IN = document.getElementById('datatablenewname'); var tabledata_newname_initialname = []; ...

Creating dynamic content in the Ajax-enabled Smart Admin theme: A step-by-step guide

As I work on developing an application for a client, my focus is on creating a web service using Laravel5 for the backend. To enhance the user interface of this web service, I have chosen to incorporate the Smart Admin Theme, specifically utilizing the Aja ...

Font Family Not Recognized in React Native

Encountering an unusual issue while working with React Native. In my button.js file, I have the following code: import Icon from "react-native-vector-icons/MaterialIcons"; const icon = (Icon name="menu size={20} color="green"/>); render() return( ...

Validation of multiple textboxes can be achieved by utilizing either JavaScript or Angular 1

How can I implement a validation in Angular 1 or JavaScript that will enable the submit button only when there is text in any of the 3 textboxes? If no text is present, the button should be disabled. Below is the code snippet: First name: <br> < ...