如何在一个组件中触发通知事件并在 Angular 4 中监听另一个组件(组件没有父/子关系) [英] How to trigger notification event in one component and listen in another component in Angular 4 (components do not have parent/child relation)

查看:38
本文介绍了如何在一个组件中触发通知事件并在 Angular 4 中监听另一个组件(组件没有父/子关系)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在另一个组件中进行一些活动后对一个组件进行更改.组件没有父/子关系.请告诉我正确的解决方案

I want to make a change in one component after some activity in another component. The components do not have a parent/child relation. Please tell me the correct solution to this

推荐答案

您可以使用私有主题和公共 observable 创建具有双向流的共享服务.两个组件都可以订阅这些 observable,其中一个可以推送新值,另一个可以根据新值变化做出反应.

you can create a shared service with bi-directional flow using private subjects and public observables. Both the components can subscribe to these observables, where one can push new values and other can react according to the new value changes.

官方文档!

plunker 中的组件没有任何父子关系.

Components in the plunker don't have any parent child relationship.

工作Plunker

 @Injectable()
export class MissionService {

  // Observable string sources
  private missionAnnouncedSource = new Subject<string>();
  private missionConfirmedSource = new Subject<string>();

  // Observable string streams
  missionAnnounced$ = this.missionAnnouncedSource.asObservable();
  missionConfirmed$ = this.missionConfirmedSource.asObservable();

  // Service message commands
  announceMission(mission: string) {
    this.missionAnnouncedSource.next(mission);
  }

  confirmMission(astronaut: string) {
    this.missionConfirmedSource.next(astronaut);
  }
}

这篇关于如何在一个组件中触发通知事件并在 Angular 4 中监听另一个组件(组件没有父/子关系)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆