您可以使用 BehaviorSubject
来在整个应用程序的不同组件之间进行通信。您可以定义一个数据共享服务,其中包含BehaviorSubject
您可以订阅和发出更改的服务。
定义数据共享服务
import { Injectable } from '@angular/core';import { BehaviorSubject } from 'rxjs';@Injectable()export class DataSharingService { public isUserLoggedIn: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);}DataSharingService
在您的 AppModule
提供商条目中添加。
接下来,将导入到
DataSharingService您
<app-header>和您在其中执行登录操作的组件中。在
<app-header>订阅
isUserLoggedIn主题更改中:
import { DataSharingService } from './data-sharing.service';export class AppHeaderComponent { // Define a variable to use for showing/hiding the Login button isUserLoggedIn: boolean; constructor(private dataSharingService: DataSharingService) { // Subscribe here, this will automatically update // "isUserLoggedIn" whenever a change to the subject is made. this.dataSharingService.isUserLoggedIn.subscribe( value => { this.isUserLoggedIn = value; }); }}在您的
<app-header>html模板中,您需要添加
*ngIf条件,例如:
<button *ngIf="!isUserLoggedIn">Login</button> <button *ngIf="isUserLoggedIn">Sign Out</button>
最后,您只需要在用户登录后发出事件,例如:
someMethodThatPerformsUserLogin() { // Some pre // ..... // After the user has logged in, emit the behavior subject changes. this.dataSharingService.isUserLoggedIn.next(true);}


