What is the best way to initialize constructor values using singleton() in TypeScript?

I am confused about passing a value in the constructor using a singleton class in TypeScript.

mycode .ts

import {singleton} from "tsyringe";

@singleton()
class Bar {
  constructor(value: string) 
{
this.value = value
}
}

// another file
import "reflect-metadata";
import {container} from "tsyringe";
import {Bar} from "./bar";

const obj = container.resolve(Bar);

Can someone provide an example code on how to pass a value in the constructor using the constainer .resolve function?

Answer №1

If you want to pass a value into the constructor, you can follow these steps:

import {injectable} from "tsyringe";

@injectable()
class Bar {
  private num: number;
  constructor(@inject("NumberValue") value: number) {
    this.num = value;
  }
}

// Another file
import "reflect-metadata";
import {container} from "tsyringe";
import {Bar} from "./bar";

const num = 42;

container.register("NumberValue", { useValue: num });
const instance = container.resolve(Bar);

Answer №2

@user1762087, in response to your inquiry, if you wish to provide distinct parameters to constructors for individual instances, a possible approach would be like this:

import "reflect-metadata";
import {container} from "tsyringe";
import {Bar} from "./bar";

const str = "example";

container.registerInstance("AnotherName", { useValue: str });
const new_instance = container.resolve(Bar);

// If needed, clear previously registered instances using registerInstance()
container.clearInstances();

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

The API endpoint returns a 404 not found error on NextJS 14 in the production environment, while it functions correctly on the local

I am in the process of creating a small website using NEXT JS 14. On my website, there is a contact us page that I have been working on. In the GetInTouch.tsx file, I have the following code: <Formik initialValues={{ ...

Transform text into clickable URL references

I have developed a unique component in NextJS that transforms a specified string within a text into a link of my choosing. export const StringToLink = ({ href, initialText, stringToReplace, useAnchorTag = false, }: { initialText: string; string ...

Angular: proper dependency injection may not occur when appending .js or .ts at the end of an import statement

When it comes to import statements, the format is usually as follows: import {HelpService} from '../../help.service' It's worth noting that if I utilize autowiring to inject HelpService into the constructor, an already existing instance of ...

Validating Components that Adhere to an Interface

When working with Angular, there is a need to specify the type for a component that implements a particular interface and is passed into a class. For example, consider Class A with the following signature: class A { constructor(public component: ?) {} } ...

Is it possible for me to distribute one Angular project that can be utilized for both Web and Ionic platforms?

Recently, I successfully developed an Angular 5 project which is now deployed on a webserver and utilized by users. The project includes @angular/material2 and angularfire5. My interest has shifted towards creating mobile applications, and I discovered th ...

Typescript array iteration using dual parameters

I seem to be struggling with the logic behind this seemingly straightforward iteration question. My task involves iterating through an array of data based on id and code, removing data only when the code is not associated with the given id's. Let&ap ...

Ensuring external library object properties are limited in Typescript

Trying to utilize the notify function from an external library has been a bit challenging. The declaration in the library is as follows: // library.js export declare const notify: { (args: NotificationsOptions | string): void; close(id: unknown): ...

Ensuring the correct class type in a switch statement

It's been a while since I've used Typescript and I'm having trouble remembering how to properly type guard multiple classes within a switch statement. class A {} class B {} class C {} type OneOfThem = A | B | C; function test(foo: OneOfThe ...

Nested self-referencing in Typescript involves a structure where

Please note that the code below has been simplified to highlight a specific issue. The explanation before the code may be lengthy, but it is necessary for clarity. Imagine I have a Foo class that represents a complex object. interface Config { bars:{ ...

Issue: The Component type is declared in 2 different modules

When including a component in the HTML of an Ionic page, I added it to the declarations array of the page.module.ts file like this: @NgModule({ imports: [ CommonModule, FormsModule, IonicModule, DeleteFriendsPageRoutingModule ], decla ...

There was an issue: Control with the name 'name' could not be located

Whenever I submit the form and try to go back, an error pops up saying "ERROR Error: Cannot find control with the name: 'name'". I'm not sure what I might be missing. Do I need to include additional checks? Below is my HTML file: <div ...

How can I transfer information from a map to a child component?

I'm attempting to transfer a variable from a parent component to a child component using React and Typescript. In my Table component (parent), I have the following map. It sets the 'data' variable as the value of the last element in the arr ...

Is there a way to navigate directly to the code in a TypeScript type definitions index.d.ts file within Visual Studio Code?

When I command-click on the express() function, it takes me to its definition: const app = express(); In vscode, it leads me to this line in an index.d.ts file: declare function e(): core.Express; However, when I try to jump to the definition of e(), i ...

Function arity-based type guard

Consider a scenario where there is a function with multiple optional parameters. Why does the function's arity not have a type guard based on the arguments keyword and what are some solutions that do not require altering the implementation or resorti ...

Unable to determine all parameters for Modal: (?, ?, ?)

import { Component, Inject } from '@angular/core'; import { NavController, Modal } from 'ionic-angular'; import { PopupPage } from '../../components/modal/modal.page'; @Component({ templateUrl: 'build/pages/spot/spot. ...

Using createContext in React.tsx to pass the state through useState

There is a context called Transaction that accepts an object and a function as parameters. In the AppProvider component, the Transaction.Provider is returned. The following code snippet is from the GlobalState.tsx file: import { createContext, useState } f ...

What is the best way to show the stored date in the input field using the GET method in mat-datepicker?

After creating a mat-datepicker and saving the selected date in the back-end, I am now wondering how to display the saved date in the input field. Below is my code snippet: // HTML <mat-form-field appearance="fill"> <mat-label>Da ...

Apply a dynamic function to assign a background color to a specific class

Currently, I have a function called getBackground(items) that returns a background color from a JSON file list. Within my application, there is a component that automatically adds a class name (.item-radio-checked) when a user clicks on an item in the list ...

Selecting from multiple options with a form control: `<mat-select>`

I am utilizing Angular material's multiple choice feature for selection purposes as demonstrated on their site https://material.angular.io/components/select/overview (8th example). In addition, I have an array containing key-value pairs that represen ...

JavaScript Equivalent to C#'s BinaryReader.ReadString() Function

Currently, I am in the process of translating C# code into JavaScript. While transferring multiple datatypes from this file to matching functionalities found in various JavaScript libraries was relatively smooth, there is one specific function that seems t ...