问题描述
当时我的项目中有五个组件
I have five components in my project at the time which are
1: AppComponent (Main component)
2: AuthComponent
3: HomeComponent
4: HeaderComponent
5: FooterComponent
AppComponent"的 Html 是
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>
现在HomeComponent"和AuthComponent"在router-outlet"中渲染,AuthComponent"有登录和注销的方法.在HeaderComponent"中有一个注销按钮,当它点击时,我想调用AuthComponent"的注销方法.现在在这里我不能使用模板变量"作为AuthComponent"在那里回答因为它在路由器插座"中呈现.那么如何做到呢?
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?
推荐答案
您必须创建一个在您的 HeaderComponent
和 AuthComponent
之间共享的公共服务,并且您可以使用该服务可以在 HeaderComponent
和 AuthComponent
之间进行通信.检查 父母和孩子通过服务进行交流 文档和我对 亲子沟通
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
这篇关于Angular 2 中的兄弟事件通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!