Angular 7: 如何发送和接收全局事件?
创始人
2024-10-16 22:31:18
0

要发送和接收全局事件,可以使用Angular的EventEmitter和Subscription。

首先,在一个全局事件服务中创建一个EventEmitter:

import { Injectable, EventEmitter } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class GlobalEventsService {
  public myEvent: EventEmitter = new EventEmitter();

  constructor() { }
}

接下来,在发送事件的组件中注入全局事件服务,并在需要发送事件的地方调用EventEmitter的emit方法:

import { Component } from '@angular/core';
import { GlobalEventsService } from 'path/to/global-events.service';

@Component({
  selector: 'app-sender',
  template: `
    
  `
})
export class SenderComponent {
  constructor(private globalEventsService: GlobalEventsService) { }

  sendEvent() {
    this.globalEventsService.myEvent.emit({ data: 'Event Data' });
  }
}

最后,在接收事件的组件中也注入全局事件服务,并订阅EventEmitter的事件:

import { Component, OnDestroy } from '@angular/core';
import { GlobalEventsService } from 'path/to/global-events.service';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-receiver',
  template: `
    

{{ receivedData }}

` }) export class ReceiverComponent implements OnDestroy { receivedData: string; private eventSubscription: Subscription; constructor(private globalEventsService: GlobalEventsService) { this.eventSubscription = this.globalEventsService.myEvent.subscribe((eventData) => { this.receivedData = eventData.data; }); } ngOnDestroy() { this.eventSubscription.unsubscribe(); } }

现在,当发送组件中的按钮被点击时,事件将被发送到接收组件,并在接收组件的模板中显示。

相关内容

热门资讯

记者揭秘!wepoker私人局... 记者揭秘!wepoker私人局辅助器怎么用,wepoker手机插件,2025新版技巧(有挂技巧);建...
记者发布!如何下载wepoke... 记者发布!如何下载wepoker安装包,微扑克微乐辅助,黑科技教程(有挂攻略)关于如何下载wepok...
揭秘关于!agpoker辅助,... 1、揭秘关于!agpoker辅助,hhpoker必备开挂,新2025教程(有挂透明)。2、hhpok...
重大发现!aapoker破解侠... 重大发现!aapoker破解侠是真的吗,cloudpoker外挂,大神讲解(有挂神器)是由北京得aa...
必看攻略!wepoker怎么下... 必看攻略!wepoker怎么下载游戏,wepoker透视脚本免费下载,详细教程(有挂技巧);致您一封...
发现一款!德州局透视脚本,HH... 发现一款!德州局透视脚本,HH平台挂,扑克教程(有挂技巧)1、很好的工具软件,可以解锁游戏的ai质量...
推荐十款!aapoker真的假... 推荐十款!aapoker真的假的,aapoker透视脚本下载,wpk教程(有挂攻略)是一款可以让一直...
一起来讨论!wepoker有辅... 1、一起来讨论!wepoker有辅助功能吗,wepoker数据分析工具,规律教程(有挂方法)2、进入...
总算了解!wepoker公共底... 1、总算了解!wepoker公共底牌,aapoker发牌逻辑,教你教程(有挂攻略)。2、aapoke...
今日头条!wepoker挂,h... 今日头条!wepoker挂,hhpoker底牌透视脚本,可靠技巧(有挂技巧);亲真的是有正版授权,小...