【问题标题】:oidc-client return false at first try in angular componentoidc-client 首次尝试在角度组件中返回 false
【发布时间】:2021-11-12 22:58:09
【问题描述】:

我开发 Angular 应用程序并使用 oauth 进行身份验证。 我安装了 oidc-client npm 包。并且各方面工作正常。 但是 ngoninit 方法有一点错误。 这是我的代码:

  ngOnInit() {
   
    this.subscription = this.authService.authNavStatus$.subscribe(status => {
      this.isAuthenticated = status;
      console.log('header'+status);
    });
  }

我在控制台看到的是这里:

如图所示,oninit 方法调用了两次。第一次返回 false 的状态,但第二次返回 true。

更多详情,我的 AuthService 在这里:

export class AuthService extends BaseService {

  // Observable navItem source
  private _authNavStatusSource = new BehaviorSubject<boolean>(false);
  // Observable navItem stream
  authNavStatus$ = this._authNavStatusSource.asObservable();

  private _loginChangedSubject = new Subject<boolean>();
  public loginChanged = this._loginChangedSubject.asObservable();

  private manager = new UserManager(getClientSettings());
  private user: User | null;

  constructor(private http: HttpClient, private configService: ConfigService) {
    super();

    this.manager.getUser().then(user => { 
      console.log(user);
      this.user = user;      
      this._authNavStatusSource.next(this.isAuthenticated());
    });

    // this.manager.events.addAccessTokenExpired(_ => {
    //   console.log(this.user);
    //   this._loginChangedSubject.next(false);
    // })
  }

  login() {
    return this.manager.signinRedirect();
  }

  async completeAuthentication() {
    this.user = await this.manager.signinRedirectCallback();
    this._authNavStatusSource.next(this.isAuthenticated());
  }

  async finishLogout() {
    this.user = null;
    this._loginChangedSubject.next(false);
    return this.manager.signoutRedirectCallback();
  }

  register(userRegistration: any) {
    return this.http.post(this.configService.authApiURI + '/account', userRegistration).pipe(catchError(this.handleError));
  }

  isAuthenticated(): boolean {
    return this.user != null && !this.user.expired;
  }

  get authorizationHeaderValue(): string {
    return `${this.user!.token_type} ${this.user!.access_token}`;
  }

  get name(): string {
    return this.user != null ? this.user.profile.name! : '';
  }

  async signout() {
    await this.manager.signoutRedirect();
  }
}

更新:

感谢@MikeOne 和@Icekson, 现在的问题是为什么状态一开始是假的,第二次是真的?

更新 2: 这是我的 header.component.html:

<pec-header [isAuth]="isAuthenticated"></pec-header>
<br>
<br>
<hr>
<h2>{{isAuthenticated}}</h2>
<hr>

header.component.ts 在这里:

export class MyHeaderComponent implements OnInit {


  private destroy$: Subject<void> = new Subject<void>();
  userPictureOnly: boolean = false;
  user: any;
  isAuth: boolean;
  name: string;
  subscription: Subscription;
  isAuthenticated: boolean;



 
  constructor(private router: Router, private helpers: Helpers, private authService: AuthService) {

  }

  ngOnInit() {
   
    this.subscription = this.authService.authNavStatus$.subscribe(status => {
      this.isAuthenticated = status;
      console.log('header component => ' + status);
    });
    this.name = this.authService.name;

  }
}

h2 标记显示 'true' 值,但 pec-header 标记的绑定值表现为假。

谢谢

【问题讨论】:

  • 这不是因为 oninit 被调用了两次。你的 observable 只发射了两次。
  • 正确同意@MikeOne
  • @MikeOne 感谢您的回复。现在的问题是“为什么状态一开始是假的,然后是真的?”。第一次尝试应该怎么做才能得到真正的结果?
  • this.authService.authNavStatus$.pipe(filter(Boolean)).subscribe(....) 应该这样做
  • @MikeOne 我添加了我的 header.component.ts 和 header.component.html

标签: angular oauth oidc-client


【解决方案1】:

ngOnInit 总是为每个组件触发一次。你有一个 Observable authStatus$ 被发射了几次,以防止这种使用 rxjs 运算符 take(1)

 ngOnInit() {
   
    this.subscription = this.authService.authNavStatus$.pipe(take(1)).subscribe(status => {
      this.isAuthenticated = status;
      console.log('header'+status);
    });
  }

【讨论】:

  • 感谢您的回复。现在的问题是“为什么状态一开始是假的,然后是真的?”。第一次尝试应该怎么做才能得到真正的结果?
  • - 您可以在 AuthService private _authNavStatusSource = new ReplaySubject&lt;boolean&gt;(1); 中将 BehaviorSubject 替换为 ReplaySubject 或者 - 您可以添加 .pipe(filter((state) =&gt; !!state)) 但请注意,在这种情况下,您的订阅回调将只处理真实结果跨度>
  • 我添加了我的 header.component.ts 和 header.component.html
猜你喜欢
  • 2021-02-06
  • 2021-01-11
  • 2018-11-29
  • 2014-06-22
  • 1970-01-01
  • 2018-01-18
  • 2017-08-15
  • 2020-12-24
  • 2022-07-10
相关资源
最近更新 更多