我的页面 struct 是:
<app-header></app-header>
<router-outlet></router-outlet>
<app-footer></app-footer>
如何在不刷新整个页面的情况下更新/刷新app-header
组件?
一旦用户成功登录,我希望隐藏标题中的"登录"链接.标题在所有组件/布线中都是通用的.
我的页面 struct 是:
<app-header></app-header>
<router-outlet></router-outlet>
<app-footer></app-footer>
如何在不刷新整个页面的情况下更新/刷新app-header
组件?
一旦用户成功登录,我希望隐藏标题中的"登录"链接.标题在所有组件/布线中都是通用的.
您可以使用100在整个应用程序的不同组件之间进行通信.您可以定义一个数据共享服务,其中包含您可以订阅和发出更改的100.
Define a data sharing service
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable()
export class DataSharingService {
public isUserLoggedIn: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
}
在您的101 Providers条目中添加100.
接下来,在<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);
}