Search code examples
angulartypescriptconstructormodel

Using service in the constructor of a MODEL (angular)


So, My goal is to use service in a model constructor because my service use info and method that my constructor could use.

For better understanding, i immagined a user case on the fly. Don't forget it's just an exemple for the problem.

Models

Let's say i've a model with dog info But also, I want the height difference with the breed 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

By change, in my service, i've a perfect function for it

In my service, all the breed info are stored. And i've function that give me the Height Diff by sending the breed.

 GetbreedDif(breed){

// FIND MY BREED

// CALCUL THE DIF

// 

return  HeightDif;
} 

Now, I want to use this specific function in MY MODELS.

What his the best way to implement it ?

My ideas

- I send the service as parameter

Constructor(id, name, breed, age, height, service){

this.id = id;
this.name = name,
this.breed = breed,
this.age = age,
this.height = height,
this.dif_Height = service.GetbreedDif(breed)

}

But I don't like to send my service this way, and think this is'nt optimal.

- I Recreate the function, using my service info as parameter

Constructor(id, name, breed, age, height, service_breedlist){

this.id = id;
this.name = name,
this.breed = breed,
this.age = age,
this.height = height,
this.dif_Height = this.GetbreedDif(breed, service_breedlist)

}
GetbreedDif(breed, MyServiceList){

// FIND MY BREED

// CALCUL THE DIF

// 

return  HeightDif;
}

Which i found better, but pretty annoying to pass something that is already fixed somehere else, especially if, for some reasons i must create a lot of object.

- Inject the service in the models ?

It's my third idea. But, i'm not sure of the exact implementation and also of the consequence of it.

- Something else ?

Is there any method i did'nt think about and would be good ?


Solution

  • If your service method does not have a state, then using a static method might be the solution here.

    // service
    export class BreedDiffService {
       static GetBreedDiff(breed) {
           // do work here
       }
    }
    
    // model constructor
    constructor(id, name, breed, age, height, service){
        this.id = id;
        this.name = name,
        this.breed = breed,
        this.age = age,
        this.height = height,
        this.difHeight = BreedDiffService.GetBreedDiff(breed)
    }
    

    Please note that this isn't using an instance of the service but instead calling the method directly through the class. I also haven't tested this but this should probably work.