如果 angular 中没有用户 logged-in,Header 应该隐藏 4
Header should hide if no user logged-in in angular 4
如果 angular 4 应用程序中没有用户 logged-in,我的要求是隐藏一个 Header。
我正在尝试在 app.component.html 和 app.component.ts
中实现它
app.component.html
<app-header *ngIf="isUserLoggedIn"></app-header>
<router-outlet></router-outlet>
app.component.ts
import { Component, OnInit } from '@angular/core';
import { AuthenticationService } from './services/authentication.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.sass']
})
export class AppComponent implements OnInit {
title = 'app';
public isUserLoggedIn: boolean;
constructor(private authService: AuthenticationService) {}
ngOnInit() {
this.isUserLoggedIn = this.authService.isUserLoggedIn(); // returns true if user logged-in otherwise returns false
console.log(this.isUserLoggedIn);
}
}
以上代码仅在页面刷新时有效,而在 url 路径更改但未刷新时无效。有 thoughts/alternate-ideas 吗?
ngOnInit
在组件初始化期间仅调用一次,因此在您刷新页面时它会起作用。
为了让它工作,创建一个函数并return它在里面
isLoggedIn(): boolean {
return this.authService.isUserLoggedIn();
}
和HTML
<app-header *ngIf="isLoggedIn()"></app-header>
如果 angular 4 应用程序中没有用户 logged-in,我的要求是隐藏一个 Header。
我正在尝试在 app.component.html 和 app.component.ts
中实现它app.component.html
<app-header *ngIf="isUserLoggedIn"></app-header>
<router-outlet></router-outlet>
app.component.ts
import { Component, OnInit } from '@angular/core';
import { AuthenticationService } from './services/authentication.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.sass']
})
export class AppComponent implements OnInit {
title = 'app';
public isUserLoggedIn: boolean;
constructor(private authService: AuthenticationService) {}
ngOnInit() {
this.isUserLoggedIn = this.authService.isUserLoggedIn(); // returns true if user logged-in otherwise returns false
console.log(this.isUserLoggedIn);
}
}
以上代码仅在页面刷新时有效,而在 url 路径更改但未刷新时无效。有 thoughts/alternate-ideas 吗?
ngOnInit
在组件初始化期间仅调用一次,因此在您刷新页面时它会起作用。
为了让它工作,创建一个函数并return它在里面
isLoggedIn(): boolean {
return this.authService.isUserLoggedIn();
}
和HTML
<app-header *ngIf="isLoggedIn()"></app-header>