簡體   English   中英

在* ngIf中使用oidc-client在Angular中實現isLoggedIn()函數

[英]Implementing isLoggedIn() function in Angular with oidc-client in *ngIf

目標:我正在嘗試使用IdentityServer4和oidc客戶端在Angular應用中隱藏和顯示Loggin和Logout按鈕。

問題:來自我的isLoggedIn函數的響應在返回true和* ngIf從不顯示“注銷”按鈕或隱藏“登錄”按鈕之前返回未定義。 看到代碼:

app.componenet.html:

<span>
      <button *ngIf="!isLoggedIn()" mat-button (click)="login()">Login</button>
      <button *ngIf="isLoggedIn()" mat-button (click)="logout()">Logout</button>
</span>

app.componenet.ts:

    isLoggedIn(){
        console.log('isLoggedIn -this._authService.isLoggedIn():',
          this._authService.isLoggedIn());
        this._authService.isLoggedIn();
      }

auth.service.ts

isLoggedIn(): boolean{
    return this._user && this._user.access_token && !this._user.expired;
  }

在auth.service.ts中,我像這樣設置用戶對象:

 this._userManager = new UserManager(config);
    this._userManager.getUser().then(user =>{
      if(user && !user.expired){
        this._user = user;
      }

console.log輸出: 在此處輸入圖片說明

我嘗試過的

  1. 我嘗試使用oidc-client版本,在leatest和1.4.1之間切換,並確保它們在package.json和我的oidc-login-redirect.html文件中匹配。
  2. 如果使用異步管道,將auth.service.ts isLoggedIn函數轉換為Promise isLoggedIn()並直接從* nf調用它

auth.service.ts Promise {返回新的Promise(resolve => {resolve(this._user && this._user.access_token &&!this._user.expired);}); }

app.component.html

  <button *ngIf="!this._authService.isLoggedIn() | async" mat-button (click)="login()">Login</button>
  <button *ngIf="this._authService.isLoggedIn() | async" mat-button (click)="logout()">Logout</button>

這兩種方法均無效,並且允諾嘗試導致google chrome掛斷: 在此處輸入圖片說明

如果您在某個角度的Angular應用程序中調用signinRedirectCallback(而不是位於SPA之外的單獨的html頁面),則很可能在調用登錄回調之前調用了設置this.user的代碼。

您應該在UserManager上訂閱addUserLoaded,並從其處理程序中在身份驗證服務中設置用戶。 這樣,您的用戶將始終保持最新狀態。

如果上面的代碼是從您的源復制/粘貼的,則您的app.component isLoggedIn不會從auth服務返回值,它只是在auth服務上調用isLoggedIn而不返回值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM