循环依赖注入angular 2 [英] Circular dependency injection angular 2
问题描述
我一直在努力将 services
注入彼此.以下博客 构造函数中的循环依赖和依赖注入在它说
I've been struggling around injecting services
into each other. The following blog Circular Dependency in constructors and Dependency Injection is kind of confusing where it says
两个对象之一隐藏了另一个对象 C
One of the two objects is hiding another object C
在相互注入服务类时出现以下错误
I get the following error while injecting Service class into each other
无法解析 PayrollService 的所有参数:(SiteService、StorageService、SweetAlertService,?)
Can't resolve all parameters for PayrollService: (SiteService, StorageService, SweetAlertService, ?)
//abstractmodal.service.ts
@Injectable()
export abstract class AbstractModel {
abstract collection = [];
constructor(private siteService: SiteService, private storageService: StorageService,
private sweetalertService: SweetAlertService) {}
setCollectionEmpty() {
this.collection = [];
}
}
//account-payable.service.ts
@Injectable()
export class AccountPayableService extends AbstractModel {
public collection = [];
constructor(private sS: SiteService,private stS: StorageService, private sws: SweetAlertService,
private accpPoService: PayablePurchaseOrderService, private attachmentService: AttachmentService,
private injectorService: InjectorService) {
super(sS, stS, sws);
}
}
//injector.service.ts
@Injectable()
export class InjectorService {
constructor(private payrollService: PayrollService) {}
cleanPayrollCollection() {
this.payrollService.setCollectionEmpty();
}
}
//payroll.service.ts
@Injectable()
export class PayrollService extends AbstractModel {
public collection = [];
constructor(private sS: SiteService,private stS: StorageService, private sws: SweetAlertService,
private accpService: AccountPayableService) {
super(sS, stS, sws);
}
}
您的评论和回答将不胜感激.
Your comments and answered will be appreciated a lot.
谢谢
推荐答案
您可以通过注入 Injector
而不是导致循环依赖的服务之一来解决循环依赖
You can workaround circular dependencies by injecting Injector
instead of one of the services that cause the circular dependency
private payrollService:PayrollService;
constructor(/*private payrollService:PayrollService*/ injector:Injector) {
setTimeout(() => this.payrollService = injector.get(PayrollService));
}
这篇关于循环依赖注入angular 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!