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

时间:2017-09-05 05:55:22

标签: javascript angular refresh angular-components

我的网页结构是:

<app-header></app-header>
<router-outlet></router-outlet>
<app-footer></app-footer>

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

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

5 个答案:

答案 0 :(得分:38)

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

定义数据共享服务

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

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

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;
        });
    }
}

<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);
}

答案 1 :(得分:2)

许多解决方案之一是创建一个@Injectable()类,其中包含要在标题中显示的数据。其他组件也可以访问此类并更改此数据,从而有效地更改标题。

另一个选项是设置@Input()变量和@Output() EventEmitters,您可以使用它们来更改标题数据。

编辑您请求的示例:

@Injectable()
export class HeaderService {
    private _data;
    set data(value) {
        this._data = value;
    }
    get data() {
        return this._data;
    }
}

在其他组成部分:

constructor(private headerService: HeaderService) {}

// Somewhere
this.headerService.data = 'abc';
标题组件中的

let headerData;

constructor(private headerService: HeaderService) {
    this.headerData = this.headerService.data;
}

我还没有尝试过这个。如果get / set不起作用,您可以将其更改为使用Subject();

// Simple Subject() example:
let subject = new Subject();
this.subject.subscribe(response => {
  console.log(response); // Logs 'hello'
});
this.subject.next('hello');

答案 2 :(得分:1)

Angular会在检测到变量变化时自动更新组件。

所以你需要做的就是刷新&#34;确保标头具有对新数据的引用。这可以通过header.component.ts内的订阅或通过@Input变量...

进行订阅

一个例子......

<强> main.html中

<app-header [header-data]="headerData"></app-header>

<强> main.component.ts

public headerData:int = 0;

ngOnInit(){
    setInterval(()=>{this.headerData++;}, 250);
}

<强烈> header.html中

<p>{{data}}</p>

<强> header.ts

@Input('header-data') data;

在上面的例子中,标题将每250ms接收一次新数据,从而更新组件。

有关Angular生命周期钩子的更多信息,请参阅:https://angular.io/guide/lifecycle-hooks

答案 3 :(得分:1)

更新组件

 @Injectable()
    export class LoginService{
    private isUserLoggedIn: boolean = false;

    public setLoggedInUser(flag) { // you need set header flag true false from other components on basis of your requirements, header component will be visible as per this flag then
    this.isUserLoggedIn= flag;
    }


public getUserLoggedIn(): boolean {
return this.isUserLoggedIn;
}

Login Component ts
            Login Component{
             constructor(public service: LoginService){}

public login(){
service.setLoggedInUser(true);
}
            }
Inside Header component

 Header Component ts
        HeaderComponent {
         constructor(public service: LoginService){}

         public getUserLoggedIn(): boolean { return this.service.getUserLoggedIn()}
        }

template of header component: Check for user sign in here

<button *ngIf="getUserLoggedIn()">Sign Out</button>
<button *ngIf="!getUserLoggedIn()">Sign In</button>

您可以使用许多方法,例如使用ngIf

显示隐藏
App Component ts
AppComponent {
 public showHeader: boolean = true;
}
App Component html
<div *ngIf='showHeader'> // you show hide on basis of this ngIf and header component always get visible with it's lifecycle hook ngOnInit() called all the time when it get visible
<app-header></app-header>
</div>
<router-outlet></router-outlet>
<app-footer></app-footer>

您也可以使用服务

@Injectable()
export class AppService {
private showHeader: boolean = false;

public setHeader(flag) { // you need set header flag true false from other components on basis of your requirements, header component will be visible as per this flag then
this.showHeader = flag;
}

public getHeader(): boolean {
return this.showHeader;
}
}

App Component.ts
    AppComponent {
     constructor(public service: AppService){}
    }

App Component.html
    <div *ngIf='service.showHeader'> // you show hide on basis of this ngIf and header component always get visible with it's lifecycle hook ngOnInit() called all the time when it get visible
    <app-header></app-header>
    </div>
    <router-outlet></router-outlet>
    <app-footer></app-footer>

答案 4 :(得分:0)

要定期刷新组件,我发现这是最好的方法。 在ngOnInit方法的setTimeOut函数中

ngOnInit(): void {
  setTimeout(() => { this.ngOnInit() }, 1000 * 10)
}
//10 is the number of seconds