2017-01-13 50 views
2

我遇到以下配置: 我使用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> 

回答

1

在我直接回答這個問題之前,我應該說明在登錄時使用路由更爲常見。如果您未通過身份驗證,則您的路由可能與「/ signIn」類似。成功驗證後,你會發送到另一個'頁面',它會呈現你的ItemsComponent(例如'/ home')。在這種情況下,除非您已登錄,否則您將看不到ItemsComponent,因此它總是會解決。因爲它是在auth發生之前加載組件,使得生活比其他情況更加困難。

如果要顯示ItemsComponent是否登錄,然後希望div在登錄時顯示,一種方法是在auth服務中創建一個經過驗證的observable並將其設置爲爲false,然後在進行身份驗證時將其設置爲true。然後在您的ItemsComponent中,您需要訂閱該可觀察值,以便在您登錄後發生更改時,您可以在成功回調中運行認證碼。基本上,這些代碼隨後會在您登錄或註銷時運行。

如果您不確定Observables,請使用路由建議。這很容易。

+0

感謝您的提示,有道理,我將探索兩種方式,並回來與反饋:) – Battalgazi

+1

解決它的方式你建議,謝謝! :D – Battalgazi

+0

太棒了!聽到那個消息很開心。 – Finnjon

相關問題