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

如何在Component 2中获取Service发射值中的data参数?

如何在Component 2中获取Service发射的data值

你现在打印的是Service里的emitChange方法本身,所以输出的是函数体。要拿到实际发射的data值,需要订阅Service暴露的changeEmitted$ Observable流,具体实现如下:

方案一:手动订阅并管理生命周期

修改Component 2的TS代码,通过订阅Observable获取发射的数据,同时在组件销毁时取消订阅避免内存泄漏:

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { MyService } from './替换为你的service文件路径';

@Component({
  selector: 'app-component2',
  templateUrl: './component2.component.html',
  styleUrls: ['./component2.component.css']
})
export class Component2 implements OnInit, OnDestroy {
  // 用于组件销毁时终止订阅的信号
  private destroy$ = new Subject<void>();

  constructor(private myService: MyService) {}

  ngOnInit(): void {
    // 订阅changeEmitted$流
    this.myService.changeEmitted$
      .pipe(takeUntil(this.destroy$))
      .subscribe(event => {
        // 直接获取data参数
        console.log('获取到的data:', event.data);
        
        // 可选:根据emitValue做针对性处理
        if (event.emitValue === 'openFunctionInSidePanel') {
          // 这里写你需要的业务逻辑,比如打开侧边栏
          console.log('触发侧边栏逻辑,传入数据:', event.data);
        }
      });
  }

  ngOnDestroy(): void {
    // 发送销毁信号,清理订阅
    this.destroy$.next();
    this.destroy$.complete();
  }
}

方案二:使用async管道(无需手动管理订阅)

如果不想写手动订阅的代码,可以用Angular的async管道,让框架自动处理订阅和取消订阅:

Component 2 TS代码

import { Component } from '@angular/core';
import { MyService } from './替换为你的service文件路径';

@Component({
  selector: 'app-component2',
  templateUrl: './component2.component.html',
  styleUrls: ['./component2.component.css']
})
export class Component2 {
  // 直接把Service的Observable暴露给模板
  changeEmitted$ = this.myService.changeEmitted$;

  constructor(private myService: MyService) {}
}

Component 2 模板代码

<!-- 使用async管道订阅流,并将数据赋值给event变量 -->
<div *ngIf="changeEmitted$ | async as event">
  发射的data值:{{ event.data }}
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 14:30:58