首页 > 解决方案 > *ngIf 异步管道问题

问题描述

我正在使用 AngularFire 对我的 Angular 11 项目进行身份验证。*ngIf我不知道为什么,但是刷新页面时我无法使用异步管道对身份验证状态做出反应。

这是我的代码:

认证服务:

[...]
export class AuthService {
  public isAuth$ = new BehaviorSubject<boolean>(false);

  constructor(private angularFireAuth: AngularFireAuth,
              public router: Router) {

    this.angularFireAuth.onAuthStateChanged((user: any) => {
      if (user) {
                                                           // On reflesh
                                                           // when signed in
        console.log('signed in');                          //display signed in
        console.log('isAuth$:', this.isAuth$.getValue());  //display false

        this.isAuth$.next(true);                           

        console.log('isAuth$:', this.isAuth$.getValue()); //display true

      } else {
        console.log('signed out');
        this.isAuth$.next(false); 
      }
    });
  }

// Some Auth functions

}

组件 .ts

[...]
export class HeaderComponent implements OnInit {

  constructor(public authService: AuthService) {}

  public isAuth$ = new BehaviorSubject<boolean>(this.authService.isAuth$.getValue());

  ngOnInit(): void {
    this.isAuth$ = this.authService.isAuth$;
  }

}

组件html:

<div>
   <a *ngIf="!(isAuth$ | async)">Sign in</a> 
   <a *ngIf="(isAuth$ | async)">Sign out</a>
<div>

正在出现的是,当我登录并刷新时。Angular 显示已注销状态,直到我单击某个字段或按钮...

从登录状态刷新时,控制台日志显示:

auth.service.ts:19 signed in
auth.service.ts:20 isAuth$: false
auth.service.ts:22 isAuth$: true

刷新时的值会发生变化,所以我假设async管道*ngIf应该对这些变化做出反应并立即显示一组好的按钮。跳上你的灯来理解这个问题。

标签: angularrxjsangularfireangular-ng-if

解决方案


应该是这样的:

export class HeaderComponent implements OnInit {

  constructor(public authService: AuthService) {}

  public isAuth$ = this.authService.isAuth$

  ngOnInit(): void {
    //this.isAuth$ = this.authService.isAuth$; --> remove this
  }
}

当您在 上使用getValue()BehaviorSubject,它只会获取该更改检测周期的值。您不需要(实际上不应该)重新isAuth$分配ngOnInit

还有html

<div>
   <a *ngIf="!(isAuth$ | async)">Sign in</a> 
   <a *ngIf="(isAuth$ | async)">Sign out</a> <!-- missing a $ here -->
<div>

您还可以对结果进行分组,例如:

<div *ngIf="isAuth$ | async as isAuth>
   <a *ngIf="!isAuth">Sign in</a> 
   <a *ngIf="isAuth">Sign out</a>
<div>

推荐阅读