我正在使用 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
管道应该对这些变化做出反应并立即显示一组好的按钮。希望你能理解这个问题。
答案 0 :(得分:1)
应该是:
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>
答案 1 :(得分:0)
我发现问题不在于管道的使用或类似的问题,而是像 eko 所说的角度检测周期。
public auth: boolean = false;
ngOnInit(): void {
ngZone.run(() => {
this.authService.auth$.subscribe((auth: boolean) => {
this.auth = auth;
});
});
}
组件
<div>
<a *ngIf="!isAuth">Sign in</a>
<a *ngIf="isAuth">Sign out</a>
<div>
工作正常。