Circular dependency injection angular 2

Basheer Kharoti picture Basheer Kharoti · Nov 10, 2016 · Viewed 12k times · Source

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

One of the two objects is hiding another object C

I get the following error while injecting Service class into each other

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.

Thanks

Answer

Günter Zöchbauer picture Günter Zöchbauer · Nov 10, 2016

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