My primary objective is to utilize a service within a model constructor that can access the necessary information and methods required by the constructor. To illustrate this concept, consider a hypothetical scenario I have concocted on the spot as an example.
Models
Suppose I have a model representing dog information, but in addition to basic details, I also want to calculate the height difference from the breed's average.
Class Dog {
id: string;
name: string;
breed: string;
age: number;
height: number;
dif_Height: number;
Constructor(id, name, breed, age, height) {
this.id = id;
this.name = name;
this.breed = breed;
this.age = age;
this.height = height;
}
}
Services
In my service class, I have implemented a function specifically designed for this purpose.
The service stores all relevant breed information and contains a function to calculate the height difference based on the breed provided.
GetbreedDif(breed) {
// LOCATE THE BREED
// CALCULATE THE DIFFERENCE
return HeightDif;
}
Now, I am looking for the best way to incorporate this function into my models.
My ideas
- Passing the service as a parameter
Constructor(id, name, breed, age, height, service) {
this.dif_Height = service.GetbreedDif(breed);
}
However, I am not entirely keen on passing the service in this manner as it may not be the most efficient approach.
- Adapting the function to use service information as parameters
Constructor(id, name, breed, age, height, service_breedlist) {
this.dif_Height = this.GetbreedDif(breed, service_breedlist);
}
GetbreedDif(breed, MyServiceList) {
// LOCATE THE BREED
// CALCULATE THE DIFFERENCE
return HeightDif;
}
Although I find this method more favorable, it could become tedious having to pass fixed information already available elsewhere, particularly when creating multiple objects.
- Injecting the service directly into the models?
This is my third proposal, but I am uncertain about the specific implementation and potential consequences.
- Any other alternatives?
Are there any other methods or strategies that I have overlooked which might offer a better solution?