Я столкнулся со следующим соотношением: Я использую Auth0 для аутентификации пользователей. Когда я первый логин, у меня есть auth.service, который извлекает профиль пользователя и сохраняет его в локальном хранилище. Эта услуга вводится в мой компонент под названием items.component. Я хочу проверить свойство моего профиля (profile.user_metadata.admin) и показать его в div моего html сразу после первого входа. Проблема в том, что профиль не будет храниться в локальном хранилище до самого конца, и я могу проверить его только в том случае, если я проверю 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