Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 routed component interaction with parent

Please consider the bellow diagram for my application

enter image description here

EventsHub is a simple injectable service :

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.

On the other hand,when I call the same service function from NavigationMenu , MainApp receives the event just fine. So how is it supposed for routed components to interact with their parent ?

Thanks

this case has been tested on RC1 & RC2

like image 373
Hasan Avatar asked Oct 18 '22 06:10

Hasan


1 Answers

Ensure you provide EventsHub only once on a common parent (root component). DI maintains a single instance for every provider. 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.

like image 193
Günter Zöchbauer Avatar answered Nov 15 '22 05:11

Günter Zöchbauer