在模型的构造函数中使用服务(角度)

问题描述 投票:0回答:1

所以, 我的目标是在模型构造函数中使用服务,因为我的服务使用我的构造函数可以使用的信息和方法。

为了更好地理解,我即时想象了一个用户案例。 不要忘记这只是问题的一个例子。

型号

假设我有一个包含狗信息的模型 但是也, 我想要与品种平均身高的差异。

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

}
}

服务

通过改变,在我的服务中,我有一个完美的功能

在我的服务中,所有品种信息都被存储。 我的功能是通过发送品种来给我高度差异。

 GetbreedDif(breed){

// FIND MY BREED

// CALCUL THE DIF

// 

return  HeightDif;
} 

现在,我想在我的模型中使用这个特定功能。

他的最佳实施方式是什么?

我的想法

- 我将服务作为参数发送

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)

}

但我不喜欢以这种方式发送我的服务,并且认为这不是最佳选择。

- 我使用我的服务信息作为参数重新创建该函数

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;
}

我发现更好,但是传递已经在其他地方修复的东西非常烦人,特别是如果由于某些原因我必须创建很多对象。

- 在模型中注入服务?

这是我的第三个想法。 但是,我不确定确切的实施方式以及其后果。

-还有什么吗?

有什么方法我没有想到并且会很好吗?

angular typescript constructor model
1个回答
0
投票

如果您的服务方法没有状态,那么使用静态方法可能是这里的解决方案。

// 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)
}

请注意,这不是使用服务的实例,而是直接通过类调用方法。我也没有测试过这个,但这应该可行。

© www.soinside.com 2019 - 2024. All rights reserved.