通过Angular的服务在两个儿童组件(兄弟姐妹组件)之间共享数据
儿童组件1
我有一个日期选择器字段,该字段将用作滤镜获取结果并在 child Component 2 中显示的过滤器。同时,我创建了一项服务,并共享来自儿童组件1的数据到该服务。
儿童组件2
我能够在ngoninit()
方法上订阅数据。
我的期望:
但是由于此日期选择器经常更改以过滤结果,因此我想在 child Component 2 外部订阅ngoninit()
IE,即我想订阅实时数据。
中没有进行代码更改
注意 :父级组件子组件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);
}
儿童组件2
this.sharedService.updateFilterDate.subscribe(dateValue => this.fromDate = dateValue);
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()
i.e 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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在儿童组件2中进行此更改
)。
this.sharedservice.filterdate $ ( 获取数据流。
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.