因此,我有一个标头组件,根据用户是否登录来显示用户名或“登录”。我还有一个登录组件,它执行登录的所有业务逻辑。它们目前没有父/子关系。
当用户登录时,除非在浏览器中完成整页刷新,否则标题不会刷新或更改。我在网上进行了大量搜索和阅读,了解实现此目的的不同方法。 ngOnChanges、NgZone、ApplicationRef 和 ChangeDetectorRef 似乎是最受欢迎的。我正在尝试在 ChangeDetectorRef 中实现此行为,因为这似乎与我的情况最相关。但是,我似乎找不到如何使用它的实际示例。
我已经编码了,但它似乎没有做任何事情。任何意见,将不胜感激。我什至接受我采取了错误的方法,需要使用除 ChangeDetectorRef 之外的另一种解决方案。
登录组件
import { Component, OnInit } from '@angular/core';
import { Response } from '@angular/http';
import { Router } from '@angular/router';
import { AuthenticationService } from '../service/authentication.service';
@Component({
selector: 'login-component',
templateUrl: './login.component.html'
})
export class LoginComponent implements OnInit {
constructor(private router: Router,
private authenticationService: AuthenticationService) { }
ngOnInit() {
// Resets the login service.
// This is one of the events that should cause the refresh.
this.authenticationService.logout();
}
login() {
/*
Authentication code
This is the other event that should cause the refresh.
*/
}
}
标头组件
import { ChangeDetectorRef, ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import { Instance } from '../../entity/instance';
@Component({
selector: 'header-component',
templateUrl: './html/header.component.html',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class HeaderComponent {
userName: string;
constructor(private ref: ChangeDetectorRef) {
this.ref.markForCheck();
}
ngOnInit(): void {
var currentUser = JSON.parse(localStorage.getItem('currentUser'));
this.userName = currentUser && currentUser.full_name;
if (!this.userName) {
this.userName = "User Name";
}
}
}
应用组件
import { ChangeDetectorRef, ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import { Instance } from './entity/instance';
import { InstanceService } from './service/instance.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class AppComponent implements OnInit {
instances: Instance[];
constructor(private instanceService: InstanceService) { }
ngOnInit(): void {
}
}
应用程序组件.html
<header-component></header-component>
<router-outlet></router-outlet>