Dependency Injection: The constructor of the injectable class is called multiple times

There are multiple classes that inject the TermsExchangeService:

import {TermsExchangeService} from './terms-exchange.service';

@injectable()
export class TermsExchangeComponent {
  constructor(
        private termsExchangeService: TermsExchangeService
    ) {}
}

and

import {TermsExchangeService} from './terms-exchange.service';

@injectable()
export class PurchaseMainComponent {
    constructor(
       private termsExchangeService: TermsExchangeService
    ) {}

The service is used in both PurchaseMainComponent and TermsExchangeComponent

@injectable()
export class TermsExchangeService {

    constructor() {
        debugger; // called 2 times!!!
    }
}

I am using autoBindInjectable:

var simpleContainer = new Container({ autoBindInjectable: true })

When retrieving components in a loop, the constructor of TermsExchangeService is called multiple times:

for (let item = 0; item < components.length; item++) {
   const container = simpleContainer.get(components[item]);
}

Why is an object created in every component? And how can normal injections be done?

Answer №1

Typically, the injectable is not considered a Singleton by default.

To address this issue, you can include defaultScope: 'Singleton':

var customContainer = new Container(
            { 
               autoBindInjectable: true, 
               defaultScope: 'Singleton'
            }
)

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

Incorrect typings being output by rxjs map

combineLatest([of(1), of('test')]).pipe( map(([myNumber, myString]) => { return [myNumber, myString]; }), map(([myNewNumber, myNewString]) => { const test = myNewString.length; }) ); Property 'length' does not ...

What causes an ObjectUnsubscribedError to be triggered when removing and then re-adding a child component in Angular?

Within a parent component, there is a list: items: SomeType; The values of this list are obtained from a service: this.someService.items$.subscribe(items => { this.items = items; }); At some point, the list is updated with new criteria: this.some ...

Send information as FormData object

I'm getting the data in this format: pert_submit: {systemId: "53183", pert-id: "176061", score: 0, q2c: "3\0", q2t: "", …} Now I need to send it as FormData in my post request. Since I can't use an ...

Retrieve every item in a JSON file based on a specific key and combine them into a fresh array

I have a JSON file containing contact information which I am retrieving using a service and the following function. My goal is to create a new array called 'contactList' that combines first names and last names from the contacts, adding an &apos ...

I am looking to append a new value to an array within the state in React

development environment ・ react ・ typescript In this setup, state groups are stored as arrays. If you want to add a group to the array of groups when the onClickGroups function is called, how should you go about implementing it? interface ISearc ...

Retrieve the value of a property with a generic type

Within our angular6 project, we encountered an issue while using the "noImplicitAny": true setting. We realized that this caused problems when retrieving values from generic types. Currently, we retrieve the value by using current['orderBy'], bu ...

Generate a new entry by analyzing components from a separate array in a single line

I have a list of essential items and I aim to generate a record based on the elements within that list. Each item in the required list will correspond to an empty array in the exist record. Essentially, I am looking to condense the following code into one ...

Component fails to navigate to the page of another component

Hello there. I am facing an issue where the button with routelink in the RegistrationComponent is not routing to the page of LogInComponent and I cannot figure out why. Angular is not throwing any errors. Here is the RouteComponent along with its view: im ...

It appears that Yarn is having trouble properly retrieving all the necessary files for a package

Recently, I encountered a strange issue in our project involving 3 microservices, all using the exceljs library. Two of the microservices successfully download all necessary files for this package through yarn. However, the third microservice is missing ...

Top method for allowing non-component functions to update Redux state without the need to pass store.dispatch() as a parameter

As I work on my first ReactJS/redux project, I find myself in need of some assistance. I've developed a generic apiFetch<T>(method, params) : Promise<T> function located in api/apiClient.ts. (Although not a React component, it is indirect ...

Using TypeScript, what is the best way to call a public method within a wrapped Component?

Currently, I'm engaged in a React project that utilizes TypeScript. Within the project, there is an integration of the react-select component into another customized component. The custom wrapped component code is as follows: import * as React from " ...

Tips for incorporating attributes into a customized Material-UI props component using TypeScript in React

I'm interested in using material-ui with react and typescript. I want to pass properties to the components, but I'm having trouble figuring out how to do it. Currently, I'm working with the react-typescript example from the material-UI repos ...

Creating Custom Type Guards for Literal Types in Typescript: Is It Possible?

Note: I am new to using typescript. Before asking this question, I made sure to go through the documentation on advanced types and type guards. Additionally, I looked into several related questions on Stack Overflow such as user defined type guards [typesc ...

Securely transfer data between objects using a for loop

Description I have two similar types that are not identical: type A = { a?: number b?: string c?: boolean } type B = { a?: number b?: string c?: string } I am looking to create an adapter function f() that can convert type A to type B, with ...

What is the code to continuously click on the "Next" button in playwright (typescript) until it is no longer visible?

Currently, I have implemented a code that clicks the next button repeatedly until it no longer appears on the pagination. Once the last page is reached, I need to validate the record. The problem arises when the script continues to search for the locator ...

Adjusting the position of Angular Mat-Badge in Chrome browser

I'm currently using the newest version of Angular and I am attempting to utilize the Angular materials mat-badge feature to show the number of touchdowns a player has thrown. However, in Chrome, the badge position seems to shift when the number is inc ...

Difficulties with managing button events in a Vue project

Just getting started with Vue and I'm trying to set up a simple callback function for button clicks. The callback is working, but the name of the button that was clicked keeps showing as "undefined." Here's my HTML code: <button class="w ...

Utilizing Angular 4's piping feature to manipulate data sourced from an API observable within

I am currently working on setting up a filter for my stories. After subscribing to the API call, I receive the data in the form of an array of objects. However, I am encountering an error while trying to apply filters. Here is a snippet of relevant inform ...

The test suite encountered an error: Invariant violation occurred because the statement "Buffer.from("") instanceof Uint8Array" was evaluated as false when it should have been

**Error: The condition "Buffer.from("") instanceof Uint8Array" is incorrectly evaluating to false This error indicates a problem with your JavaScript environment. eBuild relies on this specific condition which suggests that your JS environment is not funct ...

Stop the transmission of ts files

Recently, I noticed that when using node JS with Angular-CLI, my .ts files are being transmitted to the client through HTTP. For example, accessing http://localhost/main.ts would deliver my main.ts file to the user. My understanding is that ts files are s ...