In Child Component 1 - I am having a date picker field which will be used as a filter to fetch the results and display it in Child Component 2
As of now, I have created a service and share data from Child Component 1 to that service. In Child Component 2, I am able to subscribe to the data on ngOnInit() method.
But since this date picker changes often to filter the results, I want to subscribe to it in Child Component 2 outside ngOnInit() i.e I want to subscribe to real-time data.
Is there anyway I could do it?
Note: No code change has been made in the parent component
Child Component 1.ts
shareDate(fromDateEvent){
const fromDate = fromDateEvent.target.value;
this.sharedService.updateFilterDate(fromDate);
}
Service.ts
private filterDate = new BehaviorSubject<string>(null);
get filterDate$(): Observable<string> {
return this.filterDate.asObservable();
}
updateFilterDate(fromDate: string): void{
this.filterDate.next(fromDate);
}
Child Component 2
this.sharedService.updateFilterDate.subscribe(dateValue => this.fromDate = dateValue);
CodePudding user response:
In child component 2 make this change
this.sharedService.filterDate$().subscribe(dateValue => this.fromDate = dateValue);
You have to subscribe to the observable to get the stream of data.