Sibling event communication in Angular 2

2020-03-30 03:46发布

问题:

I have five components in my project at the time which are

1: AppComponent (Main component)
2: AuthComponent
3: HomeComponent
4: HeaderComponent
5: FooterComponent

Html for "AppComponent" is

<section class="app content-area">
<ng2-slim-loading-bar  [height]="'4px'"></ng2-slim-loading-bar>
<fds-header *ngIf="_appDataService.isLoggedIn"></fds-header>
<router-outlet></router-outlet>
<fds-footer></fds-footer>

Now "HomeComponent" and "AuthComponent" is rendering in "router-outlet" and "AuthComponent" have method for login and logout. In "HeaderComponent" there is a button for logout and when it clicked I want to call logout method of "AuthComponent". Now here I cannot use "Template variable" for "AuthComponent" as answered there because it is rendering in "router-outlet". So how it can be done?

回答1:

You have to create one common service which shared between your HeaderComponent and AuthComponent and with this service you can communicate between HeaderComponent and AuthComponent. Check Parent and children communicate via a service documentation and my answer for parent-child comunication