【发布时间】:2020-11-01 06:14:36
【问题描述】:
我想在 Angular/Typescript 中实现策略模式并在组件中使用服务;服务将策略接口作为构造函数参数。此外,约束是服务依赖于角度级别的其他一些注入服务。
我正在研究文档,但找不到解决方法。我不想以过度设计的代码而告终,寻找简单的解决方案来实现策略模式。
请看下面的模拟代码:
export interface IStrategy {
calculate(a,b): number;
}
export class MinusStrategy implements IStrategy {
calculate(a,b): number {
return a - b;
}
}
export class PlusStrategy implements IStrategy {
calculate(a,b): number {
return a + b;
}
}
@Injectable()
export class CalculatorService {
// I understand it is not possible to have DI of the Interface here for calcStrategy
constructor(private http: HttpClient; private calcStrategy: IStrategy);
getByCalc() {
this.http.get('someurl?calc=' + calcStrategy.calculate(1,1));
}
}
@Component(// skipped config here...)
export class MyComponent implements OnInit {
// How to inject appropriate concrete strategy (and either autowire or provide httpClient?)
constructor(private service: new CalculatorService(httpClient, new MinusStrategy()));
useInComponent() {
this.service.getByCalc();
}
}
【问题讨论】:
标签: angular typescript design-patterns