如果没有用户登录到Angular4应用程序,我的要求是隐藏一个头。
我试图在app.component.html和app.component.ts中实现它
app.component.html软件

<app-header *ngIf="isUserLoggedIn"></app-header>
<router-outlet></router-outlet>

应用组件
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路径更改而不刷新时则不起作用。有什么想法/其他想法吗?

最佳答案

在组件初始化时只调用一个,这样当刷新页面时它会起作用。
为了让它工作,创建一个函数并将其返回到内部

 isLoggedIn(): boolean {
     return this.authService.isUserLoggedIn();
 }

和HTML
<app-header *ngIf="isLoggedIn()"></app-header>

关于angular - 如果没有用户以 Angular 4登录,则标题应隐藏,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48139922/

10-11 13:08