【发布时间】:2018-08-06 00:57:38
【问题描述】:
组件:
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);
}
}
【问题讨论】: