如何在不刷新整个页面的情况下更新组件 - Angular [英] How to Update a Component without refreshing full page - Angular
问题描述
我的页面结构是:
<app-header></app-header>
<router-outlet></router-outlet>
<app-footer></app-footer>
如何在不刷新整个页面的情况下更新/刷新 app-header
组件?
How can I update/refresh the app-header
component, without refreshing the whole page?
我想在用户成功登录后隐藏标题中的登录"链接.标题在所有组件/路由中都是通用的.
I want to hide a "Sign-In" link in the header, once the user had successfully logged in. The header is common in all the components/routes.
推荐答案
您可以使用 BehaviorSubject
在整个应用程序的不同组件之间进行通信.您可以定义包含 BehaviorSubject
的数据共享服务,您可以订阅和发出更改.
You can use a BehaviorSubject
for communicating between different components throughout the app. You can define a data sharing service containing the BehaviorSubject
to which you can subscribe and emit changes.
定义数据共享服务
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable()
export class DataSharingService {
public isUserLoggedIn: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
}
在您的 AppModule
提供程序条目中添加 DataSharingService
.
Add the DataSharingService
in your AppModule
providers entry.
接下来,在您的
和您执行登录操作的组件中导入 DataSharingService
.在
中订阅对 isUserLoggedIn
主题的更改:
Next, import the DataSharingService
in your <app-header>
and in the component where you perform the sign-in operation. In <app-header>
subscribe to the changes to isUserLoggedIn
subject:
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;
});
}
}
在您的
html 模板中,您需要添加 *ngIf
条件,例如:
In your <app-header>
html template, you need to add the *ngIf
condition e.g.:
<button *ngIf="!isUserLoggedIn">Login</button>
<button *ngIf="isUserLoggedIn">Sign Out</button>
最后,您只需要在用户登录后发出事件,例如:
Finally, you just need to emit the event once the user has logged in e.g:
someMethodThatPerformsUserLogin() {
// Some code
// .....
// After the user has logged in, emit the behavior subject changes.
this.dataSharingService.isUserLoggedIn.next(true);
}
这篇关于如何在不刷新整个页面的情况下更新组件 - Angular的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!