Indhu
Indhu

Reputation: 399

Angular How to resolve circular dependency within services

I need to communicate between two services where it has dependency on both A->B and B->A. But getting circular dependency error on achieving it.

@Injectable()
export class ServiceA{
 constructor(private serviceB:ServiceB){
 }
 OnInit(){
 this.serviceA.Callme();
 }
afterServiceBInitialization(){
//doing logic here
}
}
@Injectable()
export class ServiceB{
 constructor(private serviceA:ServiceA){
 }
 Callme(){
  console.log("hello");
 this.serviceA.afterServiceBInitialization()
 }
}

But getting circular dependency error. How to proceed with this ?

Upvotes: 0

Views: 1014

Answers (1)

Goht
Goht

Reputation: 56

You can import a service into another service, but two services cannot be imported into each other or it creates a circular dependency issue.

You can instead import both services into a component and pass values through the component instead of direct from service to service.

for example:

import { firstService } from '../services/first.service';
import { secondService } from '../services/second.service';

@Component({
...
})
export class MyComponent implements OnInit, {

 constructor(
   private first: FirstService,
   private second: SecondService
 ) { }

 ngOnInit(): void {
   second.value = first.value
 }
}

Upvotes: 1

Related Questions