Angular 6-在组件加载后更新* ngIf

时间:2018-08-06 00:57:39

标签: angular angular6

组件:

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

// Services
import { AuthService } from './services/auth.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.less']
})
export class AppComponent implements OnInit {
  user: Object;
  authorized: boolean;

  constructor(private authService: AuthService) {}

  ngOnInit() {
    this.authorized = this.authService.loggedIn();
  }
}

HTML:

<app-navbar *ngIf="authorized"></app-navbar>

<div id="content"
     *ngIf="authorized">
    <app-sidebar></app-sidebar>

    <div class="wrapper full-width">
        <router-outlet></router-outlet>
    </div>
</div>

<div class="container mt-6"
     *ngIf="!authorized">
    <router-outlet></router-outlet>
</div>

this.authService.loggedIn();返回true或false,用于显示HTML的* ngIf中的某些元素。登录后,用户将重定向到该页面,因此* ngIf不会自动读取。相反,您必须刷新页面以使所有内容正确更新。

据我所知,我无法订阅this.authService.loggedIn(),因为它不是可观察的,所以我不确定在用户首次查看组件时如何自动更新视图。以下是服务本身供参考:

loggedIn() {
    if (localStorage.id_token === undefined ) {
      return false;
    } else {
      const helper = new JwtHelperService();
      return !helper.isTokenExpired(localStorage.id_token);
    }
  }

1 个答案:

答案 0 :(得分:2)

您可以通过使其成为吸气剂来确保authorized属性是最新的:

public get authorized(): boolean {
  return this.authService.loggedIn();
}