2

I need to pass data from Service1 to Service2

Service1

@Injectable()
export class Service1 {
    ...
}

similar for Service2

the only way I found to make Service1 communicate with Service 2 is using window['var'] (set in Service1, read in Service2)

I think this is more a "hack" than a real solution but injecting a 3rd service doesn't work.

Another solution is using localStorage but yet doesn't seem ideal to me.

Any clue?

dragonmnl
  • 14,578
  • 33
  • 84
  • 129

1 Answers1

1

You can just inject one service into another

@Injectable()
class Service2 {
  // constructor(private service2:Service2) {}
  // cyclic dependencies are not supported
  // therefore only one service can inject the other, 
  // but both directions at the same time causes an exception

  someProp:String = 'xxx';
}

@Injectable()
class Service1 {
  constructor(private service2:Service2) {
    console.log(service2.someProp);
  }
}

See also DI with cyclic dependency with custom HTTP and ConfigService

You can also use observables so that one service can subscribe to changes in the other service.

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567