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()