1

来自 oidc-client 在 Angular 10 构造函数中的承诺需要太长时间才能解决,在构造函数将 de 值放入用户变量之前调用 isLoggedIn 函数。

这是我的代码:

import { UserManager, UserManagerSettings, User } from 'oidc-client';

export class AuthService {
  private user: User = null;
  private manager = new UserManager(getClientSettings());
  privatecachedRequests: Array<HttpRequest<any>> = [];

  constructor() {
    this.manager.getUser().then(user => {
      this.user = user;
    });
  }
  isLoggedIn(): boolean {
    return this.user != null && !this.user.expired; <= this.user is null because the constructor did not finished the async part
  }

此代码在角度 8 中工作

当我在 isLoggedIn 方法中调用 getUser() 函数时,它起作用了,但我想从构造函数中使用它

4

1 回答 1

1

使用RxjsSubject 作为代理。

import {Subject } from 'rxjs',<-- add this
export class AuthService {
  private user: User = null;
  private manager = new UserManager(getClientSettings());
  privatecachedRequests: Array<HttpRequest<any>> = [];
  private loginSubject= new Subject()<-- add this line

  constructor() {
    this.manager.getUser().then(user => {
      this.user = user;
      if(this.user != null && !this.user.expired)
       {
         this.loginSubject.next(true)
       } else{
           this.loginSubject.next(false)
          }
     
    });
  }
  isLoggedIn(): Observable<boolean> {
     return this.loginSubject.asObservbale();<-- avoid leak 
  }

你可以在 canActivate 中返回 Observable

import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import {map} from 'rxjs/operators';


@Injectable()
export class AuthGuard implements CanActivate {

  constructor(private authService:AuthService, private router: Router) { }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean>  {
    return this.authService.isLoggedIn().pipe(
      map(res => {
        if (res) {
          return true;
        } else {
          this.router.navigate(['/login']);
           return false
        }
      })
  }   

}
于 2020-08-17T05:45:38.137 回答