您可以使用 BehaviorSubject 在整个应用程序的不同组件之间进行通信。您可以定义一个包含 BehaviorSubject 的数据共享服务,您可以订阅和发出更改。
定义数据共享服务
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable()
export class DataSharingService {
public isUserLoggedIn: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
}
在您的 AppModule 提供者条目中添加 DataSharingService。
接下来,在您的<app-header> 和您执行登录操作的组件中导入DataSharingService。在<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 code
// .....
// After the user has logged in, emit the behavior subject changes.
this.dataSharingService.isUserLoggedIn.next(true);
}