简体   繁体   English

Angular2路由组件与父组件的交互

[英]Angular2 routed component interaction with parent

Please consider the bellow diagram for my application 请考虑我的应用程序的波纹管图

在此输入图像描述

EventsHub is a simple injectable service : EventsHub是一个简单的注射服务:

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

@Injectable()
export class EventsHub {
    private announcementSource = new Subject<string>();
    messageAnnounced$ = this.announcementSource.asObservable();

    announce( message : string)  {
        console.log('eventHub : firing...'+message);
        this.announcementSource.next(message);
   }
} 

The problem is when 'announce' function is called from within Funds,Clients or any other component inside the router-outlet , the parent (MainApp) will not receive any messages. 问题是当从“基金”,“客户”或路由器插座内的任何其他组件调用“通知”功能时,父(MainApp)将不会收到任何消息。

On the other hand,when I call the same service function from NavigationMenu , MainApp receives the event just fine. 另一方面,当我从NavigationMenu调用相同的服务功能时,MainApp接收该事件就好了。 So how is it supposed for routed components to interact with their parent ? 那么如何让路由组件与其父组件进行交互呢?

Thanks 谢谢

this case has been tested on RC1 & RC2 此案例已在RC1和RC2上进行了测试

Ensure you provide EventsHub only once on a common parent (root component). 确保在公共父组件(根组​​件)上仅提供一次EventsHub DI maintains a single instance for every provider. DI为每个提供商维护一个实例。 If you provide it at every component that uses it every component gets a different instance. 如果您在使用它的每个组件上提供它,则每个组件都会获得不同的实例。 So one component listens on one instance and the other emits on another one. 因此,一个组件侦听一个实例,另一个组件侦听另一个实例。

For example your Funds component could have an EventEmitter 例如,您的Funds组件可能有一个EventEmitter

@Output() someEvent: EventEmitter<SomeResult> = new EventEmitter<SomeResult>();

Then your Funds could emit this event my calling: 然后你的基金可以发出这个事件我的呼吁:

this.someEvent.emit({'Hello', 'from', 'the', 'other','side'});

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

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