javascript - 使用 *ngIf 中的 oidc-client 在 Angular 中实现 isLoggedIn() 函数

标签 javascript angular identityserver4 openid-connect

目标:我尝试使用 IdentityServer4 和 oidc 客户端在 Angular 应用程序中隐藏和显示登录和注销按钮。

问题:我的 isLoggedIn 函数的响应在返回 true 之前返回 undifined,并且 *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 输出: enter image description here

我尝试过的:

  1. 我尝试使用我的 oidc-client 版本,切换 在leatest和1.4.1之间并确保它们匹配 package.json 和我的 oidc-login-redirect.html 文件。
  2. 将 auth.service.ts isLoggedIn 函数转换为 Promise isLoggedIn() 并使用异步管道直接从 *nfIf 调用它

auth.service.ts promise { 返回新的 Promise(解决 => { 解析(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>

这些事情都不起作用,并且 promise 尝试导致 google chrome 挂起: enter image description here

最佳答案

如果您在 Angular 应用程序中的某处(而不是位于 SPA 外部的单独 html 页面)调用signinRedirectCallback,则您的代码设置 this.user 可能会在调用登录回调之前被调用。

您应该在 UserManager 上订阅 addUserLoaded ,并在您的身份验证服务的处理程序中设置用户。这样您的用户将始终保持最新状态。

如果上面的代码是从您的源代码复制/粘贴的,则您的 app.component isLoggedIn 不会从 auth 服务返回值,它只是在 auth 服务上调用 isLoggedIn 但不返回该值。

关于javascript - 使用 *ngIf 中的 oidc-client 在 Angular 中实现 isLoggedIn() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56811876/

相关文章:

Angular 2+/4/5/6/7 : Smart, 愚蠢和深层嵌套的组件通信

migration - 将 IdentityServer4 从 v3 迁移到 v4

javascript - 通过元素传递鼠标悬停

JetBrains IDE : type-hinting the autonomous custom element instance 上的 Javascript

javascript - 仅当对象不是 undefined 时才向对象添加属性

javascript - 如何有效地对复杂的 JSON 对象进行排序?

asp.net-web-api - 使用 Asp.Net Core Web API 进行授权

c# - IdentityServer4 unsupported_grant_type 错误

javascript - 如何使用 scrollTop 作为百分比而不是像素

javascript - 使用 jQuery 的 mousedown 和 mouseup 方法时如何使用 event.preventDefault()?