What is the process for generating an injected and a const object instance?

How can an instance of class A obtain a dependency on an instance of class O, while remaining a singleton for others?

@injectable()
class O{}

// A must be single instance!
@injectable()
class A{
    constructor(o: O){
        console.log( 'is A instance' );
    }
}
@injectable()
class B{
    constructor(a: A){
        console.log( 'is B instance' );
    }
}
@injectable()
class C{
    constructor(a: A){
        console.log( 'is C instance' );
    }
}
@injectable()
class D{
    constructor(b: B, c: C){
        console.log( 'is D instance' );
    }
}


let container = new Container();
container.bind<B>( O ).to( O );
container.bind<B>( A ).toConstantValue( A ); // ?
container.bind<B>( B ).to( B );
container.bind<C>( C ).to( C );
container.bind<D>( D ).to( D );

container.get<D>(D);

Answer №1

Unable to locate the information in the official documentation, but one possible solution is suggested here -

@injectable()
class O{}

// A must be single instance!
@injectable()
class A{
    constructor(o: O){
        console.log( 'is A instance' );
    }
}
@injectable()
class B{
    constructor(a: A){
        console.log( 'is B instance' );
    }
}
@injectable()
class C{
    constructor(a: A){
        console.log( 'is C instance' );
    }
}
@injectable()
class D{
    constructor(b: B, c: C){
        console.log( 'is D instance' );
    }
}


let container = new Container();
container.bind<O>( O ).to( O );
container.bind<A>( A ).to( A ).inSingletonScope();
container.bind<B>( B ).to( B );
container.bind<C>( C ).to( C );
container.bind<D>( D ).to( D );

container.get<D>(D);

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

Extract Method Parameter Types in Typescript from a Generic Function

Can we retrieve the type of parameters of methods from a generic interface? For instance, if we have: interface Keys { create: any; ... } type MethodNames<T> = { [P in keyof Keys]: keyof T; } Then, is it feasible to obtain the type of paramete ...

Establishing the placement of map markers in Angular

Currently, I am in the process of developing a simple web application. The main functionality involves retrieving latitude and longitude data from my MongoDB database and displaying markers on a map, which is functioning correctly. However, the issue I&apo ...

The replacer argument of the JSON.stringify method doesn't seem to work properly when dealing with nested objects

My dilemma is sending a simplified version of an object to the server. { "fullName": "Don Corleone", "actor": { "actorId": 2, "name": "Marlon", "surname": "Brando", "description": "Marlon Brando is widely considered the greatest movie actor of a ...

having trouble retrieving 200 status code from Angular server response

Objective: I need to make certain changes to the record locally if the server responds with a 200 code. Problem: I am unable to retrieve the response code or access the 'message' attribute. This is the server response I receive from the HTTP ca ...

The Relationship between Field and Parameter Types in TypeScript

I am currently working on a versatile component that allows for the creation of tables based on column configurations. Each row in the table is represented by a specific data model: export interface Record { attribute1: string, attribute2: { subAt ...

The 'setComputed' property is not mandatory in the type definition, however, it is a necessary component in the 'EntityExample' type

I'm encountering an issue while trying to create a factory for updating an entity. The error I'm facing is related to the usage of afterload: Entity: import { Entity, PrimaryGeneratedColumn, Column, OneToMany, BaseEntity, AfterLoad, ...

react Concealing the Card upon clicking a different location

Utilizing a combination of React and TypeScript, this component allows for the card to be toggled between shown and hidden states upon clicking on the specified div tag. However, there is a need to ensure that the card is hidden even if another area outs ...

Creating a table with merged (colspan or rowspan) cells in HTML

Looking for assistance in creating an HTML table with a specific structure. Any help is appreciated! Thank you! https://i.stack.imgur.com/GVfhs.png Edit : [[Added the headers to table]].We need to develop this table within an Angular 9 application using T ...

What is the proper way to implement ref in typescript?

Currently, I am in the process of learning how to use Vue3 + Typescript. Previously, I have developed Vue2 applications using plain JavaScript. In my current project, I am attempting to define a reactive variable within the setup() function: setup() { ...

Generating instances using TypeScript generics

Looking to create a factory for instantiating classes with generics. After checking out the TypeScript docs, everything seems to work as expected. Here's a simplified version of how it can be done: class Person { firstName = 'John'; ...

Having trouble compiling the Electron App because of a parser error

Struggling to set up a basic electron app using Vue 3 and Typescript. Following the successful execution of certain commands: vue create app_name cd .\app_name\ vue add electron-builder npm run electron:serve Encountering issues when trying to i ...

Risky assignment of an 'any' value" encountered while implementing react-transition-group in TypeScript

Encountering @typescript-eslint errors while implementing the Transition component from react-transition-group. Implemented the official React Transition Group example for JS in a TypeScript + ESLint project, resulting in the error message: Unsafe assignm ...

CoursesComponent does not contain a Directive annotation

I have been following a tutorial online at this link: https://www.youtube.com/watch?v=_-CD_5YhJTA Unfortunately, I keep encountering the following error message: EXCEPTION: No Directive annotation found on CoursesComponent Here is an excerpt from my a ...

Error in declaring type even after including .d.ts file

I have encountered a situation where the npm package update-immutable does not come with a built-in typescript definition or a definition in @types. To resolve this issue, I created a type definition file within my project. As a result, VS Code is now able ...

An issue arises in Typescript when attempting to pass an extra prop through the server action function in the useForm

I am struggling with integrating Next.js server actions with useFormState (to display input errors on the client side) and Typescript. As per their official documentation here, they recommend adding a new prop to the server action function like this: expo ...

ag-grid-angular failing to present information in a table layout

I have implemented ag-grid-angular to showcase data in a structured table format, but the information appears jumbled up in one column. The data for my ag-grid is sourced directly from the raw dataset. https://i.stack.imgur.com/sjtv5.png Below is my com ...

Extending the Object prototype within an ES6 module can lead to errors such as "Property not found on type 'Object'."

There are two modules in my project - mod1.ts and mod2.ts. //mod1.ts import {Test} from "./mod2"; //LINE X interface Object { GetFooAsString(): string; } Object.prototype.GetFooAsString = function () { return this.GetFoo().toString(); } //mod2. ...

Angular's ng-model is unable to access the value of an object array

When selecting the days, users should be able to input check-in and check-out time ranges dynamically. However, there seems to be an issue with retrieving the values and data format. The ng model is unable to capture the check-in and check-out values. The ...

Exploring Angular component testing through jasmine/karma and utilizing the spyOn method

I have been facing an issue while trying to test my component. Even though the component itself works perfectly, the test keeps generating error messages that I am unable to resolve. Here is the snippet of code that I am attempting to test: export cl ...

Exploring Click Events in Angular with OpenLayers Features

After creating a map with parking points as features, I now want to implement a click function for the features. When a feature is clicked, I want to display a popup with the corresponding parking data. I've tried searching online for information on ...