Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
348 views
in Technique[技术] by (71.8m points)

Circular dependency injection angular 2

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...