我的 Angular 应用程序中有一个服务,它的构造函数中需要两个依赖项:UntypedFormGroup 和 DestroyRef。目前,我将这些依赖项直接注入到我的模块中的服务构造函数中。
现在,我想找到一种方法,从组件向服务提供这些依赖项,而不将它们注入到组件的构造函数中。
这是我的简化服务:
@Injectable()
export class CalculateFieldsService {
constructor(
private jsonForm: UntypedFormGroup,
private destroy: DestroyRef
) {
// Service constructor
}
// Rest of the service code...
}
我如何传递这两个参数。来自提供商或我怎样才能?
我感谢任何有关如何有效实现这一目标的指导或示例。谢谢您的协助!
您可以使用 Angular 的依赖注入系统。您可以尝试使用工厂函数来提供服务。
@Injectable()
export class CalculateFieldsService {
constructor(
private jsonForm: UntypedFormGroup,
private destroy: DestroyRef
) {
// Service constructor
}
// Rest of the service code...
}
export function CalculateFieldsServiceFactory(jsonForm: UntypedFormGroup, destroy: DestroyRef) {
return new CalculateFieldsService(jsonForm, destroy);
}
在您的组件中,您可以在组件装饰器中配置提供者以使用工厂函数提供依赖项和服务。
import { Component, Injectable, Inject } from '@angular/core';
@Component({
selector: 'app-your-component',
templateUrl: './your-component.component.html',
providers: [
{
provide: CalculateFieldsService,
useFactory: CalculateFieldsServiceFactory,
deps: [UntypedFormGroup, DestroyRef]
}
]
})
export class YourComponent {
constructor(private calculateFieldsService: CalculateFieldsService) {
// You can now use the service with the provided dependencies.
}
}