简体   繁体   English

从服务注入组件发出的捕获事件

[英]Catch event emitted from service injected into component

I have inserted a service component (component A) via dependency injection, and this service component A is not inside the template of component B. 我已经通过依赖关系注入插入了一个服务组件(组件A),并且该服务组件A不在组件B的模板内。

How can I catch an event emitted from the service component - how to catch it inside parent component (component B)? 如何捕获服务组件发出的事件-如何在父组件(组件B)内部捕获事件? I already put the emitting command inside child component like so: 我已经将发出命令放在子组件中,如下所示:

@Output() hostReady = new EventEmitter();

and I am emitting the event like so: 我发出这样的事件:

hostReady.emit();

What do I need to do in order to catch it in parent? 我需要怎么做才能被父母抓住?

Well, since I haven't posted my solution before, I might as well do it now. 好吧,由于我以前从未发布过解决方案,所以我现在也可以这样做。 So, what I did is I had a pattern Subscriber implemented. 所以,我要做的是实现了一个模式订户。 All of the components that want to know about an event are subscribed to it, and when an event is triggered they know about it. 想要了解事件的所有组件都已订阅该事件,并且在触发事件时,他们也知道该事件。 The solution deals with rxjs objects: 该解决方案处理rxjs对象:

import { Subject } from 'rxjs/Subject';

I have a special component intercommService that declares an event as an rxjs Subject, like this: 我有一个特殊的组件intercommService ,将一个事件声明为rxjs主题,如下所示:

selectedLanguage: Subject<string>;
constructor() {
    this.selectedLanguage = new Subject<any>(); 
}

Then, every component (that also has this dependency injected) can trigger the event, using this: 然后,每个组件(也注入了此依赖项)可以使用以下命令触发事件:

this.intercomm.selectedLanguage.next(language);

And each subscriber component will have this as its subscription to that event, ie, in constructor, a subscriber will have that dependency injected, and will observe its event: 每个订阅者组件将对此作为对该事件的订阅,即,在构造函数中,订阅者将注入该依赖项,并将观察其事件:

constructor(private intercomm: IntercommService) {
    this.intercomm.selectedLanguage.asObservable().subscribe((value: any) => {
        // Do something with value
    });
}

There are different ways to do it. 有不同的方法可以做到这一点。

have a look in the cookbook examples. 看看食谱示例。

https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#child-to-parent https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#child-to-parent

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM