Reputation: 26772
I have a simple chat app made with Angular 2. My application, like most Angular 2 applications, start with an AppComponent
, which uses router-outlet
to render the child components based on routing.
In a ChatComponent
I am injecting back the AppComponent
.
constructor( @Inject(forwardRef(() => AppComponent)) app: AppComponent) { .. }
I do this because this AppComponent
is also the gateway to the chat server. So no matter on what page you are, chats will always be received by the application.
The AppComponent
class also has a public usersOnline
array which is a list of all the current online users.
This is maybe not the most sexy way, but it does the trick for me. So far so good.
Whenever I navigate to my ChatComponent
, how can I then setup some sort of event listener, so that this component can do certain things when the AppComponent
updates the usersOnline
property?
Upvotes: 1
Views: 182
Reputation: 14385
Change the usersOnline
to an observable (or specifically, a subject) and then in your ChatComponent
do:
app.usersOnline$.subscribe(value => ({value handler code>});
or, if it is something you need in your template:
<div>Number of online users {(app.usersOnline$ | async).?length}</div>
In your AppComponent
change the assignment from:
this.usersOnline = <some_value>;
to
this.usersOnline$.next(<some_value>);
Upvotes: 1