如何更新组件而不刷新整页 - 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 within 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);
}
添加 DataSharingService $ c您的
。 AppModule
提供商条目中的$ c>
接下来,在< app-header> $中导入
DataSharingService
c $ c>并在您执行登录操作的组件中。在< app-header>
订阅对的更改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;
});
}
}
在< app中-header>
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屋!