我遇到以下配置: 我使用Auth0進行用戶身份驗證。當我第一次登錄,我有一個auth.service檢索用戶配置文件並將其存儲在本地存儲。這個服務被注入到我的名爲items.component的組件中。我想檢查我的個人資料(profile.user_metadata.admin)的屬性,並在第一次登錄後在我的html權限的div中顯示它。問題是配置文件不會被存儲在本地存儲中,直到最後,我只能檢查它,如果我檢查ngAfterViewChecked(),如果我在開發人員模式下運行會引發錯誤。我怎樣才能更早得到我的個人資料?或者以另一種方式進行支票?提前致謝。當第一次登錄成功太遲時獲得Auth0用戶配置文件
auth.service.component.ts
@Injectable()
export class Auth {
// Configure Auth0
lock = new Auth0Lock('xxxhiddenxx', 'xxxhiddemxxx', {});
profile:any;
constructor(private authHttp: AuthHttp, private router: Router) {
// Add callback for lock `authenticated` event
// this.userProfile = JSON.parse(localStorage.getItem('profile'));
this.lock.on("authenticated", (authResult:any) => {
this.lock.getUserInfo(authResult.accessToken, function(error:any, profile:any){
if(error){
throw new Error(error);
}
localStorage.setItem('id_token', authResult.idToken);
localStorage.setItem('profile', JSON.stringify(profile));
});
});
}
public login() {
// Call the show method to display the widget.
this.lock.show();
}
public authenticated() {
// Check if there's an unexpired JWT
// This searches for an item in localStorage with key == 'id_token'
return tokenNotExpired();
}
items.component.ts
export class ItemsComponent implements OnInit {
items: Item[];
isAdmin:boolean;
profile:any;
constructor(private ItemService:ItemService,private auth:Auth, private authHttp: AuthHttp, private router: Router){
this.ItemService.getItems()
.subscribe(items =>{
this.items=items;
//this.profile=JSON.parse(localStorage.getItem('profile'));
//this never finds the profile when first login occurs
});
}
ngAfterViewChecked(){ //only way I can get the profile data when first login
this.profile=JSON.parse(localStorage.getItem('profile'));
if(this.profile!=undefined && this.profile!=null){
console.log(this.profile.user_metadata.admin)
if(this.profile.user_metadata.admin==1){
this.isAdmin=true;
}
}
}
items.component.html
<div class="row" *ngIf="auth.authenticated()" style="margin: 20px 20px">
<div class="alert alert-success col-md-3 center" *ngIf="isAdmin===true">Admin account</div>
</div>
感謝您的提示,有道理,我將探索兩種方式,並回來與反饋:) – Battalgazi
解決它的方式你建議,謝謝! :D – Battalgazi
太棒了!聽到那個消息很開心。 – Finnjon