I encountered a challenging scenario in an actual project where I found the need for two services to access each other's properties and methods. Despite my limited expertise in Angular, I wondered if this is even possible?
I made an attempt, but unfortunately, it didn't succeed. Here's what I tried:
app.component.ts
import { Component } from '@angular/core';
import { FirstService } from './first.service';
import { SecondService } from './second.service';
@Component({
selector: 'my-app',
template: '<h1>Hello world!</h1>',
providers: [FirstService, SecondService]
})
export class AppComponent {
constructor(public firstService: FirstService, public secondService: SecondService) {
console.log(firstService.foo);
console.log(secondService.bar);
}
}
first.service.ts
import { Injectable } from '@angular/core';
import { SecondService } from './second.service';
@Injectable()
export class FirstService {
foo: string = 'abc';
constructor(public secondService: SecondService) {
this.foo = this.foo + this.secondService.bar;
}
}
second.service.ts
import { Injectable } from '@angular/core';
import { FirstService } from './first.service';
@Injectable()
export class SecondService {
bar: string = 'xyz';
constructor(public firstService: FirstService) {
this.bar = this.bar + this.firstService.foo;
}
}
Plunker: http://plnkr.co/edit/PQ7Uw1WHpvzPRf6yyLFd?p=preview
While simply injecting the second service into the first service works fine, incorporating the first service into the second service results in errors being thrown to the console.
What could possibly be the issue here?
An effective solution would display the following log in the console:
abcxyz
xyzabc
Your insights are greatly appreciated!