如何在Angular 2中将数据从子视图传递到主视图?

问题描述:

我在主视图上有两个按钮:登录和注销。最初只有登录按钮后系统显示:如何在Angular 2中将数据从子视图传递到主视图?

...

<button type="button" routerLink="/login" routerLinkActive="active" class="btn btn-info">Login</button> 
<button type="button" routerLink="/showlist" routerLinkActive="active" class="btn btn-info" (click)="logout()">Logout</button> 

<router-outlet></router-outlet> 

登录按钮,将显示一个子认为,一旦用户通过验证后在那里,我想通过结果返回给主视图,如果用户是经过身份验证,我想隐藏“登录”按钮并显示“注销”按钮。

如何通过'router-outlet'将数据从子视图传递回主视图?

+2

使用通用服务。阅读这个,我相信你会找到适合你的案例(https://angular.io/docs/ts/latest/cookbook/component-communication.html) – methgaard

您将希望使用服务在组件之间共享信息。用户通过身份验证后,您需要在此服务中设置一个属性,以指示用户已通过身份验证。

一旦你这样做了,你可以引用这个服务来确定你是否应该使用* ngIf显示隐藏的东西。

Here是一个回答的问题,是类似于你的。

+0

是的,我创建了一个共享数据服务被两个组件(主视图和子视图)引用,并且它很好地工作。感谢您的帮助! –

为了显示和隐藏按钮,您将使用* ngif结构指令,如:

<button *ngIf="!loggedIn" type="button" routerLink="/login" routerLinkActive="active" class="btn btn-info">Login</button> 
<button *ngIf="loggedIn" type="button" routerLink="/showlist" routerLinkActive="active" class="btn btn-info" (click)="logout()">Logout</button> 

的的loggedIn应与主视图相关联的部件一个布尔值。 我想,术语主视图和子视图是指您分别有一个父组件和一个子组件(用于身份验证)窗体。如果是这种情况,请参阅Component Interaction并选择最适合您的通信。