I have created 2 components and one service as below,
@Injectable()
export class ComponentInteractionService {
public dataSubject = new BehaviorSubject<string>("Test");
getTestData(): Observable<any> {
return this.dataSubject.asObservable();
}
pustTestData(dataToPush: string): void {
this.dataSubject.next(dataToPush);
}
}
export class FirstComponent {
constructor(private componentInteractionService: ComponentInteractionService) {
componentInteractionService.getTestData().subscribe(data=> {
console.log("Received at 1 -- " + data);
});
}
sendTestData(): void {
this.componentInteractionService.pustTestData("sending data from 1");
}
}
export class SecondComponent {
constructor(private componentInteractionService: ComponentInteractionService) {
componentInteractionService.getTestData().subscribe(data=> {
console.log("Received at 2 -- " + data);
});
}
}
The issue I am currently facing is
On page load both the components subscribers are being triggered, but when I push data using sendTestData() method in FirstComponent, only the subscriber in FirstComponent is being triggered. The subscriber in SecondComponent is not being triggered. What should I do for both subscribers to get triggered on pushing data using the sendTestData() method?
My Console logs are as below..
Received at 1 -- Test
Received at 2 -- Test
Received at 1 -- sending data from 1
Expected Output..
Received at 1 -- Test
Received at 2 -- Test
Received at 1 -- sending data from 1
Received at 2 -- sending data from 1
It is because you provide the same service twice in both AppComponentOne
and AppComponentTwo
so they both have different instances of the same service.
Empty providers
array of both component and provide the service within app.module.ts
@Component({
selector: 'app-distinct-first-component',
template: '<button (click)="sendTestData()">Click to send Data</button>',
providers: [ComponentService] // <= remove this line from both components
})
app.module.ts
@NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ AppComponent, HelloComponent,
FirstComponent, SecondComponent
],
bootstrap: [ AppComponent ],
providers: [ComponentService] // <= provide it here
})
export class AppModule { }