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 . Meanwhile, I have created a service and share data from Child Component 1 to that service.
Child Component 2
I am able to subscribe to the data on ngOnInit()
method.
My expectation :
But since this date picker changes often to filter the results, I want to subscribe to it in Child Component 2 outside ngOnInit()
ie I want to subscribe to real-time data.
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);
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.