简体   繁体   English

ANGULAR - 下面的 EventEmitter 服务是如何工作的?

[英]ANGULAR - How the EventEmitter Service below, works exactly?

On my work, we've been using this service below to subscribe and emit notifications right and fourth.在我的工作中,我们一直在使用下面的这个服务来订阅和发出通知。 As a junior developer I already understand Input and Outputs of Angular and sort of how Emitters work.作为一名初级开发人员,我已经了解 Angular 的输入和输出以及发射器的工作原理。

But this service simplys confuse me.但是这项服务让我很困惑。 The dev who made this service already left the company and since this code is almost a boilerplate for all projects, I cannot ask him how exactly it works.提供这项服务的开发人员已经离开了公司,因为这段代码几乎是所有项目的样板,我不能问他它是如何工作的。

specifically this line: private static emitters: { [notificationName: string]: EventEmitter } = {}特别是这一行:私有 static 发射器:{ [notificationName: string]: EventEmitter } = {}

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

@Injectable({ providedIn: 'root' })
export class EventEmitterService {

    private static emitters: { [notificationName: string]: EventEmitter<any> } = {}

    static get(notificationName: string): EventEmitter<any> {
        if (!this.emitters[notificationName])
            this.emitters[notificationName] = new EventEmitter<any>();
        return this.emitters[notificationName];
    }
}

/** 
to SUBSCRIBE:

private subscriptions = new Subscription();   
constructor(){
    this.subscriptions.add( EventEmitterService.get("notification_name").subscribe(payload => this.notificationHandler(payload)) );
}

TO EMIT: 

EventEmitterService.get("notificationName").emit(payload); 

to UNSUBSCRIBE:

ngOnDestroy(){
    this.subscriptions.unsubscribe();
}
*/

Following instructions from the user Michael D, I've change the code按照用户 Michael D 的指示,我更改了代码

import { Subject } from 'rxjs';

private emitters: { [notificationName: string]: Subject<any> } = { };

and got this error:并得到这个错误:

错误

The error was caused because the return of static get(notificationName: string): was not changed to Observable<any>错误是因为static get(notificationName: string):的返回没有更改为Observable<any>

So the final form of service, updated according to MichaelD comment:所以最终的服务形式,根据 MichaelD 的评论更新:

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

@Injectable({ providedIn: 'root' })
export class EventEmitterService {

    // private static emitters: { [notificationName: string]: EventEmitter<any> } = {}
    private  emitters: { [notificationName: string]: Subject<any> } = {};


    get(notificationName: string): Observable<any>{
        if (!this.emitters[notificationName])
            this.emitters[notificationName] = new EventEmitter<any>();
        return this.emitters[notificationName];
    }
}

Event Emitter model basically follows the observable pattern.事件发射器 model 基本上遵循可观察模式。 In above code I we created a static emitter means we can call it without an instance of class.在上面的代码中,我们创建了一个 static 发射器,这意味着我们可以在没有 class 实例的情况下调用它。 So this will five us a behavior like utility.所以这将给我们五个类似效用的行为。 You need to understand only one thing.你只需要了解一件事。 Emitters are constantly listening to the Events and as the event happens they emit the response regardless of success or failure.发射器不断地监听事件,当事件发生时,无论成功或失败,它们都会发出响应。 This response is pretty similar to the interrupt generated by hardware in our OS which make the CPU to listen that specific interrupt instead of doing other tasks.这个响应与我们操作系统中的硬件产生的中断非常相似,它使 CPU 监听该特定中断而不是执行其他任务。 So when we have an update in out Event EventEmitter will broadcast that change and our listeners will detect it on that specific Event因此,当我们在 out Event 中有更新时,EventEmitter 将广播该更改,并且我们的侦听器将在该特定事件上检测到它

I've been seeing this pattern of using EventEmitters in services frequently.我经常看到这种在服务中使用EventEmitters的模式。 EventEmitters are NOT meant to used in services. EventEmitters打算在服务中使用。 It is used to emit custom events from components to it's parent components.它用于从组件向其父组件发出自定义事件。

The EventEmitter is an interface extension of RxJS Subject . EventEmitter是 RxJS Subject的接口扩展。 If a multicast observable is required in the service, then the RxJS Subject (or BehaviorSubject ) could be used.如果服务中需要多播 observable,则可以使用 RxJS Subject (或BehaviorSubject )。

In your case, the emitter variable is an object with a property notificationName that will point to the emitter.在您的情况下, emitter变量是一个 object,其属性notificationName将指向发射器。

Also I do not understand the meaning of static here.另外我不明白static这里的含义。 The service is already made a singleton with the { providedIn: 'root' } argument.该服务已经使用{ providedIn: 'root' }参数生成了 singleton。 There isn't going to be multiple instances of the emitters . emitters不会有多个实例。

You could also have the same behavior with the following您也可以使用以下相同的行为

import { Subject } from 'rxjs';

private emitters: { [notificationName: string]: Subject<any> } = { };
private static emitters: { [notificationName: string]: EventEmitter } = {}

This line just means that emitters is an internal property of the EventEmitterService class of type object, for which keys are strings, and values instances of EventEmitter .此行仅表示emitters是类型为 object 的EventEmitterService class 的内部属性,其中键是字符串,值是EventEmitter的实例。 It's being used to keep track of active subscriptions.它被用来跟踪活动订阅。 The consumers of the service are not concerned with other consumers, they just want to emit or subscribe to a given notification, that's why it's private.服务的消费者不关心其他消费者,他们只想emitsubscribe给定的通知,这就是为什么它是私有的。

If you look at the EventEmitter interface, you'll see that you can indeed either emit or subscribe .如果您查看EventEmitter接口,您会发现您确实可以emitsubscribe When you emit you send a payload that will be passed as a parameter to the function consumers subscribed with.当您发出时,您发送一个有效载荷,该有效载荷将作为参数传递给订阅的 function 消费者。

When you subscribe to an EventEmitter , it returns a subscription which you can then unsubscribe from.当您subscribe EventEmitter时,它会返回一个订阅,然后您可以unsubscribe When you add your EventEmitter subscription to subscriptions , you're allowing yourself to be able to unsubscribe to all of them at once by calling its unsubscribe .当您将EventEmitter订阅添加到subscriptions时,您可以通过调用其unsubscribe来一次取消订阅所有订阅。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 该Angular 2应用程序中的服务层次结构到底如何工作? - How exactly works the services hierarchy in this Angular 2 application? 在这个 Angular 2 示例中,这个 Observable 行为究竟是如何工作的? - How exactly works this Observable behavior in this Angular 2 example? 有关自定义事件绑定的Angular 2教程的工作原理是什么? - How exactly works this Angular 2 tutorial about custom event binding? Angular 2属性绑定到底如何工作? 在这个例子中到底发生了什么? - How exactly works the Angular 2 property binding? What really happens in this example? 在这个Angular 2应用程序中,这个交叉组件通信“模式”究竟是如何工作的? - How exactly works this cross components comunication “pattern” in this Angular 2 application? 如何在 Angular 2 中从父级调用 @Input EventEmitter - How to call @Input EventEmitter from parent in Angular 2 我应该在 Angular 中的可重用组件中使用 EventEmitter 还是共享服务? - Should I use EventEmitter or shared Service in a reusable component in Angular? 如何从EventEmitter侦听器函数调用NestJs微服务? - How to call a NestJs micro-service from an EventEmitter listener function? Aurelia的Angular 2 EventEmitter - Angular 2 EventEmitter in Aurelia Angular 2 EventEmitter性能 - Angular 2 EventEmitter performance
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM