Javascript 使用*ngIf中的oidc客户端在Angular中实现isLoggedIn()函数

Javascript 使用*ngIf中的oidc客户端在Angular中实现isLoggedIn()函数,javascript,angular,identityserver4,openid-connect,Javascript,Angular,Identityserver4,Openid Connect,目标:我试图使用IdentityServer4和oidc客户端在Angular应用程序中隐藏和显示Loggin和Logout按钮 问题:来自my isLoggedIn函数的响应在返回true之前返回Undefined,*ngIf从不显示注销按钮或隐藏登录按钮。见代码: app.componenet.html: <span> <button *ngIf="!isLoggedIn()" mat-button (click)="login()">Login</

目标:我试图使用IdentityServer4和oidc客户端在Angular应用程序中隐藏和显示Loggin和Logout按钮

问题:来自my isLoggedIn函数的响应在返回true之前返回Undefined,*ngIf从不显示注销按钮或隐藏登录按钮。见代码:

app.componenet.html:

<span>
      <button *ngIf="!isLoggedIn()" mat-button (click)="login()">Login</button>
      <button *ngIf="isLoggedIn()" mat-button (click)="logout()">Logout</button>
</span>
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输出:

我所尝试的:

我试着玩我的oidc客户端版本,切换 在leatest和1.4.1之间,并确保它们在 package.json和我的oidc-login-redirect.html文件。 将auth.service.ts isLoggedIn函数转换为promise isLoggedIn,并使用异步管道从*nfIf直接调用它 auth.service.ts 允诺{ 返回新PromiseSolve=>{ 解决此问题。_user&&this。_user.access\u token&&this。_user.expired; }; }

app.component.html

这两件事都不起作用,谷歌chrome也因此挂断了电话:

如果您在Angular应用程序的某个地方调用SignInDirectCallback,而不是SPA之外的单独html页面,则很可能是在调用signin回调之前调用了您的代码设置this.user

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


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

我认为您没有包含足够的代码来解决此问题。没有理由必须将代码包装在承诺中或使用异步。延迟必须发生,因为任何设置都是如此。\u用户。这是有意义的,因为在oidc_客户端中,您必须调用manager.getUser,它将返回一个承诺。所以有多个状态,未知,loggedin,loggedout。一定要考虑到这一点。@DanielGimenez我添加了设置这一点的代码。\u用户,如果您对缺少的内容有任何建议,请告诉我。我希望authService保留一个行为主题或类似的内容,并在用户登录时发出一个值。这将使组件中的所有内容更加清晰,其中本地变量cam将设置在ngOnInit上,并且您的模板将仅基于该本地变量谢谢您的帮助。我在另一个文件中有SignInDirectCallback。问题的原因是我忘记返回值:。在愚昧的一天工作、让孩子上床睡觉、只睡几个小时、喝太多咖啡之后编写代码不是一个好主意。谢谢
 this._userManager = new UserManager(config);
    this._userManager.getUser().then(user =>{
      if(user && !user.expired){
        this._user = user;
      }
  <button *ngIf="!this._authService.isLoggedIn() | async" mat-button (click)="login()">Login</button>
  <button *ngIf="this._authService.isLoggedIn() | async" mat-button (click)="logout()">Logout</button>