0

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 ?

Indhu
  • 371
  • 1
  • 5
  • 18
  • Does this answer your question? [Services depending on each other](https://stackoverflow.com/questions/36378751/services-depending-on-each-other) – zronn Mar 08 '22 at 13:18
  • Thanks!Tried all solutions still issue persist. – Indhu Mar 09 '22 at 05:35

1 Answers1

1

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
 }
}
Goht
  • 46
  • 7