Guide on Integrating Dependencies into a Class

In my setup, I have two key services - CarsController and CarsFetcherService.

Additionally, there is a crucial class named Car.

The CarsController contains a method called createCar() which instantiates a new Car object every time it is invoked. Each instance of Car requires access to the CarsController service.

The issue arises where each Car instance receives 'undefined' instead of the required CarsController dependency. I have used the typedi library to showcase this problem and am seeking input on how to resolve it. Inputs using other libraries like Inversify, Nestjs or even Angular would be greatly appreciated as well.


export class Car {
    @Inject() // unfortunately not functional in this context
    private carsController: CarsController; // ends up being undefined
    private carRecipe: string;

    constructor(carRecipe: string) {
        this.carRecipe = carRecipe;
        this.carsController.notifyNetwork('HelloWorld, I am created!');
    }
}

@Service()
export class CarsController {

    @Inject()
    private carsNetworkService: CarsFetcherService;
    private cars: Car[] = [];

    constructor() {
    }

    createCar() {
        const carRecipe = this.carsNetworkService.getRequestSomething();
        const car = new Car(carRecipe);
        this.cars.push(car);
    }

    notifyNetwork(msg: string) {
        this.carsNetworkService.postRequestSomething(msg);
    }
}

@Service()
export class CarsFetcherService {
    getRequestSomething() {
        return 'this is how to make a car';
    }

    postRequestSomething(msg:string) {
        console.log(msg)
    }
}

const carsController = Container.get(CarsController)
// Creating 4 cars
carsController.createCar()
carsController.createCar()
carsController.createCar()
carsController.createCar()

Answer №1

In my opinion, it is beneficial to categorize your classes when utilizing a DI framework like typedi. One category should consist of services, where typedi ensures single instances and handles injection. The other category should comprise ordinary objects that you manually create and manage.

For example, if you need multiple instances of the Car class, avoid using DI for it. Instead, create it within a service with direct dependencies to fulfill its requirements:

export class Car {
    // inject decorator removed

    constructor(private carsController, private carRecipe: string) {
        this.carsController.notifyNetwork('HelloWorld, I am created!');
    }
}

@Service()
export class CarsController {

    @Inject()
    private carsNetworkService: CarsFetcherService;
    private cars: Car[] = [];

    constructor() {
    }

    createCar() {
        const carRecipe = this.carsNetworkService.getRequestSomething();
        const car = new Car(this, carRecipe);
        this.cars.push(car);
    }

    notifyNetwork(msg: string) {
        this.carsNetworkService.postRequestSomething(msg);
    }
}

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

Updating website elements using jQuery

Hello, I'm just starting out as a web developer and I have this script: function updateBaskket(productId, quantity) { $.ajax({ type: 'GET', url: '/update-basket', dataType: "json ...

Issues arise when Angular Meteor fails to load the UI-Router properly

Currently, I am exploring the integration of ui-router for routing within a meteor-angular application. My reference point is the meteor Whatsapp tutorial which can be found here Below is the relevant code snippet related to ui-router implementation: log ...

Python's yield functionality facilitates the creation of lightweight generators, allowing

Request is being sent from the front end to trigger the backend method. In Python Flask, the backend method utilizes a generator and yield to iterate through a list of 100000 elements, sending each element one by one to the front end. The goal is for the b ...

Displaying a segment of information extracted from a JSON array

I'm currently tackling a project that involves using React, Redux, and TypeScript. Within the JSON file, there is a key-value pair: "data_start": "2022-09-02" Is there a way to display this date in a different format, specifical ...

Safari does not respond to the dropdown function

Currently in the process of developing my website, using Bootstrap and Javascript (including jQuery). I have a navigation menu bar featuring a dropdown menu that should slide down upon hovering on mouse-enabled devices, and otherwise activate upon click/ ...

Does anyone have experience using the useRef hook in React?

Can someone help me with this recurring issue: "Property 'value' does not exist on type 'never'" interface InputProps { name: string; icon?: ReactElement; placeholder?: string; } const Input = ({ name, icon: Icon, ...rest }: Inpu ...

Steps for invoking a method on page refresh across all pages with vue.js

It is essential for the following function to run on every page refresh, regardless of the current route. For example: this.executeonEverypage() ...

create a symbol marker using highchart

I recently discovered a feature in highchart that allows me to set a marker for a specific value. According to the highchart documentation: ... data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, { y: 26.5, marker: { symbol: &ap ...

Unable to perform type casting with Firebase Admin and Google Cloud Functions

Currently facing an issue with type casting variables as the types seem impossible to import through firebase-admin. Here's a simplified example: import * as functions from 'firebase-functions' import * as admin from 'firebase-admin&ap ...

What is the best way to send variables to a jQuery function?

I'm trying to create a form where I can hide unnecessary lines by toggling them with buttons using jQuery. I've managed to start working on a page, but I'm concerned about having to write a separate function for each button, which could beco ...

Switching React Icons when Clicked

I'm struggling to understand this. I want the React icons below to be filled and remain filled when clicked, changing back to outlined when another is clicked. Here's the code: import { useState } from "react"; import { Link } from "react-router- ...

Updating Form Based on Array Changes Using React Hook Form

I am currently working on a cocktail recipe form using React-Hook-Form. One of the key features is adding ingredients to the recipe. Initially, only one row is displayed, but upon clicking the "Add ingredient" button, another row should appear. Although I ...

Executing a function on every page load in React: A step-by-step guide

One of my functions takes the height of an element and applies that same height to another element. My idea is to execute this function every time the page loads or refreshes, as well as whenever the window gets resized. // Navigation Components Resize Lo ...

Is there a way to dynamically adjust a node's rotation using both jQuery and vanilla JavaScript, incorporating the transform property rotate(30deg)?

1. When aiming to support as many browsers as possible, which of the following is the optimal choice?: -webkit-transform: rotate(30deg); -moz-transform: rotate(30deg); -ms-transform: rotate(30deg); -o-transform: rotate(30deg); transform: rotate(30deg); ...

Dropmenu | Designing with Materials | Pair of Choices | Intersection

My goal is to incorporate dropdown fields with material design only. After researching various examples online, I have noticed a recurring issue. When there are two dropdown items close to each other, they end up overlapping. Check out this example: http ...

Interacting with CouchDB using AJAX

Currently, I am creating a sample project using CouchDB. My plan is to develop a web application with AJAX and host it in the tomcat environment. I am interested in learning how to effectively communicate with the CouchDB server. While researching, I came ...

Show the coordinates x and y on a map using React JS

Is there a way to display a marker on the map in React JS using x and y coordinates instead of latitude and longitude? In my Json-file, I have x and y coordinates like "gpsx":6393010,"gpsy":1650572. I've tried using Point for x and y but can't ...

How to generate a JSON key-value pair?

I have 2 sets of arrays with the exact same length : var set1= ["apple", "banana", "orange", "mango", "grape", "kiwi", "pear", "papaya"] var set2 = ["junglebook", &qu ...

Looking for a way to scroll images without relying on the marquee tag? Whether you prefer using JavaScript, jQuery,

<marquee> <div class="client"> <img src="images/c1.png"/> </div> <div class="client"> <img src="images/c2.png"/> </div> <div class="client"> ...

Adjust the dimensions of a div using hidden ghost content as the basis

Is there a way to size a <div> element based on ghost content instead of the actual visible content? For example, can we make the box with content "A" appear as if it contains "BCD"? .container { display: flex; width: 10em; } .item { flex-grow: 1; ...