Angular 2中的同级事件通信 [英] Sibling event communication in Angular 2

查看:94
本文介绍了Angular 2中的同级事件通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当时我的项目中有五个组成部分

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",并且"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?

推荐答案

您必须创建一个在HeaderComponentAuthComponent之间共享的通用服务,并且可以使用此服务在HeaderComponentAuthComponent之间进行通信.检查父母和子女通过服务进行沟通文档和亲子沟通

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中的同级事件通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆