I am trying to pass data between two components say, B and C which are at the same level and are being used by one component say, A.
Now in template of A I am using B and C like this:
<div><b></b></div>
<div><c></c></div>
B is a dropdown component and the C component wants to use the selected dropdown value.
I have created a service to get the dropdown value like this:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class PassValueService {
private valueSource = new Subject<Array<string>>();
value$ = this.valueSource.asObservable();
passValue(data: Array<string>) {
console.log('inside pass value service', data);
this.valueSource.next(data);
this.valueToBePassed = data;
}
}
Now in C component I am trying to subscribe to the event like this:
constructor(private passValueService: PassValueService)
this.subscription = this.passValueService.value$.subscribe(data=> {
console.log('constructor', data);
});
I tried doing it in constructor, ngOnInit, ngDoCheck but with no help.
Can any body help me understand why I am not getting the value from the Observable? Let me know if there is another approach that can be used.
A simpler way for siblings is to use template variables and binding
where C has an input
For your service, ensure it is provided only once. For example in the parent component. If the service is provided at B or C, then it can't be shared between siblings.
If you provide it in
@NgModule()
then your whole application shares the same instance. This will only work ifB
andC
are only used once at the same time in your entire application.