通过Angular的服务在两个儿童组件(兄弟姐妹组件)之间共享数据

发布于 2025-02-09 12:16:51 字数 1022 浏览 2 评论 0原文

儿童组件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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

╰つ倒转 2025-02-16 12:16:51

在儿童组件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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文