You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在无关联的组件之间共享数据?附Angular场景代码示例

无关联组件间传递lastUpdatedTime的解决方案

在Angular中,无关联组件(非父子、无路由关联)之间传递数据,最可靠的方式是使用共享服务结合RxJS的BehaviorSubject,以下是具体实现步骤:

1. 创建共享数据服务

创建一个全局注入的服务,用来存储和分发lastUpdatedTime的值:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class SharedDataService {
  // 用BehaviorSubject保存当前值,初始值为空字符串
  private lastUpdatedTimeSubject = new BehaviorSubject<string>('');
  // 对外暴露Observable,避免外部直接修改Subject
  public lastUpdatedTime$ = this.lastUpdatedTimeSubject.asObservable();

  // 更新时间的方法
  updateLastUpdatedTime(time: string): void {
    this.lastUpdatedTimeSubject.next(time);
  }
}

2. 修改源组件(From Component)

在源组件中注入共享服务,当获取到lastUpdatedTime后,通过服务分发这个值:

import { Component } from '@angular/core';
import { MyService } from './my.service'; // 替换为你的实际服务路径
import { SharedDataService } from './shared-data.service'; // 替换为共享服务的实际路径

@Component({
  selector: 'app-from-component',
  templateUrl: './from-component.component.html'
})
export class FromComponent {
  lastUpdatedTime: string = '';
  tableLoading: boolean = false;

  constructor(
    private myService: MyService,
    private sharedDataService: SharedDataService
  ) {}

  getParameter() {
    this.tableLoading = true;
    this.myService.getConParameters().subscribe(
      (data) => {
        this.lastUpdatedTime = data.createdAt;
        // 将最新时间发送到共享服务
        this.sharedDataService.updateLastUpdatedTime(this.lastUpdatedTime);
        this.tableLoading = false;
      },
      (_error) => {
        this.tableLoading = false;
      }
    );
  }
}

3. 修改目标组件(To Component)

在目标组件中注入共享服务,订阅lastUpdatedTime$ Observable来接收更新的值,同时记得在组件销毁时取消订阅,避免内存泄漏:

import { Component, OnInit, OnDestroy } from '@angular/core';
import { SharedDataService } from './shared-data.service'; // 替换为共享服务的实际路径
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-to-component',
  templateUrl: './to-component.component.html'
})
export class ToComponent implements OnInit, OnDestroy {
  lastUpdatedTime: string = '';
  private timeSubscription!: Subscription;

  constructor(private sharedDataService: SharedDataService) {}

  ngOnInit(): void {
    // 订阅时间更新
    this.timeSubscription = this.sharedDataService.lastUpdatedTime$.subscribe(time => {
      this.lastUpdatedTime = time;
    });
  }

  ngOnDestroy(): void {
    // 组件销毁时取消订阅
    if (this.timeSubscription) {
      this.timeSubscription.unsubscribe();
    }
  }
}

目标组件的模板保持不变:

<p class="adjust-space">{{ lastUpdatedTime }} : </p>

说明

  • 使用BehaviorSubject而非普通Subject的原因:它会保存当前的最新值,当目标组件晚于源组件初始化时,能立即获取到已更新的lastUpdatedTime,而不会错过数据。
  • 全局注入的服务(providedIn: 'root')确保整个应用中只有一个实例,保证数据传递的一致性。

内容的提问来源于stack exchange,提问作者anonymous

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 00:26:17