如何更新组件而不刷新整页 - Angular

Ara*_*n M 36 javascript refresh angular-components angular

我的页面结构是:

<app-header></app-header>
<router-outlet></router-outlet>
<app-footer></app-footer>
Run Code Online (Sandbox Code Playgroud)

如何在app-header不刷新整个页面的情况下更新/刷新组件?

我想在用户成功登录后隐藏标题中的"登录"链接.标题在所有组件/路由中都很常见.

Fai*_*sal 46

您可以使用a BehaviorSubject在整个应用程序中的不同组件内进行通信.您可以定义包含BehaviorSubject可以订阅和发出更改的数据共享服务.

定义数据共享服务

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable()
export class DataSharingService {
    public isUserLoggedIn: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
}
Run Code Online (Sandbox Code Playgroud)

添加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;
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

在您的<app-header>html模板中,您需要添加*ngIf条件,例如:

<button *ngIf="!isUserLoggedIn">Login</button> 
<button *ngIf="isUserLoggedIn">Sign Out</button>
Run Code Online (Sandbox Code Playgroud)

最后,您只需要在用户登录后发出事件,例如:

someMethodThatPerformsUserLogin() {
    // Some code 
    // .....
    // After the user has logged in, emit the behavior subject changes.
    this.dataSharingService.isUserLoggedIn.next(true);
}
Run Code Online (Sandbox Code Playgroud)

  • 您可以将令牌保存在本地存储中,然后将“CanActivate”“Guard”添加到您的登录组件路由中。在守卫中,检查令牌是否存在,然后将用户带到所需的路线。 (2认同)
  • 非常感谢@Faisal它也很好用 (2认同)