0

菜单组件(应仅在成功登录后可见)

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from '../../services/auth.service';

@Component({
  selector: 'app-menu',
  templateUrl: './menu.component.html'
})
export class MenuComponent implements OnInit {

  public isLoggedIn = false;
  constructor(private authService: AuthService, public router: Router) {
    this.isLoggedIn = authService.loggedIn();
  }

  ngOnInit() {
  }
}

菜单组件模板

<nav role="navigation" *ngIf="isLoggedIn">
    <ul><li>Admin Menu Item</li></ul>
</nav>

主要内容组件

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-main-content',
  templateUrl: './main-content.component.html'
})
export class MainContentComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

主要内容组件模板

<div class="content">
  <div class="wrapper">
    <div class="row">
      <app-menu></app-menu>
    </div>
  </div>
</div>

应用组件模板

我正在研究使用*ngIf指令来根据用户是否登录来处理菜单组件的可见性。从上面的代码可以看出,该属性从函数中isLoggedIn分配了一个布尔值。loggedIn()

我认为到目前为止一切都很简单,但问题是菜单组件在成功登录后没有立即显示,我必须刷新浏览器才能看到菜单。不太清楚为什么会出现这种情况。有什么建议或想法吗?

4

1 回答 1

0

这是因为您的菜单组件中的 loggedIn 值仅在 ngOnInit 中设置。

改用吸气剂,如下所示:

export class MenuComponent implements OnInit {

  public get loggedIn() { return this.authService.loggedIn(); }
  constructor(private authService: AuthService, public router: Router) {
  }

  ngOnInit() {
  }
}
于 2017-06-30T02:53:01.693 回答