目标:我尝试使用 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;
}
我尝试过的:
- 我尝试使用我的 oidc-client 版本,切换 在leatest和1.4.1之间并确保它们匹配 package.json 和我的 oidc-login-redirect.html 文件。
- 将 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>
最佳答案
如果您在 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/