【发布时间】:2018-03-28 18:03:39
【问题描述】:
我有一个组件,它作为它的一部分根据配置文件对象呈现用户的名称。
一个模板对应的部分是:
<button mat-button [matMenuTriggerFor]="userMenu" *ngIf="isAuthenticated()">
{{profile?.name}}
</button>
并且配置文件正在该组件的 onInit 函数中加载:
ngOnInit() {
if (this.authService.userProfile) {
this.profile = this.authService.userProfile;
} else {
this.authService.getProfile((err, profile) => {
this.profile = profile;
});
}
}
当我第一次导航到此页面时,不会呈现名称,即使 isAuthenticated 总是返回 true。
如果我刷新页面,它会开始正确呈现。
我做错了什么?
之后,又进行了一些挖掘,似乎它只发生在身份验证之后。
这里是 AuthService 代码:
import { Injectable } from '@angular/core';
import * as auth0 from 'auth0-js';
import { environment } from '../../../environments/environment';
import { Router } from '@angular/router';
@Injectable()
export class AuthService {
auth0 = new auth0.WebAuth(environment.auth0);
userProfile: any;
constructor(private router: Router) {
}
public login(): void {
this.auth0.authorize();
}
public handleAuthentication(): void {
this.auth0.parseHash((err, authResult) => {
if (authResult && authResult.accessToken && authResult.idToken) {
window.location.hash = '';
this.setSession(authResult);
this.router.navigate(['']);
} else if (err) {
this.router.navigate(['']);
console.log(err);
}
});
}
private setSession(authResult): void {
// Set the time that the Access Token will expire at
const expiresAt = JSON.stringify((authResult.expiresIn * 1000) + new Date().getTime());
localStorage.setItem('access_token', authResult.accessToken);
localStorage.setItem('id_token', authResult.idToken);
localStorage.setItem('expires_at', expiresAt);
}
public logout(): void {
// Remove tokens and expiry time from localStorage
localStorage.removeItem('access_token');
localStorage.removeItem('id_token');
localStorage.removeItem('expires_at');
// Go back to the home route
this.router.navigate(['']);
}
public isAuthenticated(): boolean {
// Check whether the current time is past the
// Access Token's expiry time
const expiresAt = JSON.parse(localStorage.getItem('expires_at'));
return new Date().getTime() < expiresAt;
}
public getProfile(cb): void {
const accessToken = localStorage.getItem('access_token');
if (!accessToken) {
throw new Error('Access Token must exist to fetch profile');
}
const self = this;
this.auth0.client.userInfo(accessToken, (err, profile) => {
if (profile) {
self.userProfile = profile;
}
cb(err, profile);
});
}
}
【问题讨论】:
-
有变化 changeDetectionStrategy 吗?
-
请出示您的
authService的代码。