[英]*ngIf async pipe issue
我正在使用 AngularFire 對我的 Angular 11 項目進行身份驗證。 我不知道為什么,但是刷新頁面時,我無法使用異步*ngIf
對 auth state 做出反應。
這是我的代碼:
認證服務:
[...]
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 顯示已注銷的 state,直到我單擊某個字段或按鈕...
從登錄 state 刷新后,控制台日志顯示:
auth.service.ts:19 signed in
auth.service.ts:20 isAuth$: false
auth.service.ts:22 isAuth$: true
刷新時的值更改,因此我假設*ngIf
的async
pipe 應該對這些更改做出反應並立即顯示一組好的按鈕。 跳上你的燈來理解這個問題。
應該是這樣的:
export class HeaderComponent implements OnInit {
constructor(public authService: AuthService) {}
public isAuth$ = this.authService.isAuth$
ngOnInit(): void {
//this.isAuth$ = this.authService.isAuth$; --> remove this
}
}
當您在BehaviorSubject
上使用getValue()
時,它只會獲取該更改檢測周期的值。 您不需要(實際上不應該)在ngOnInit
上重新分配isAuth$
還有 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>
我發現問題不是 pipe 使用或類似的東西,而是像 eko 所說的 angular 檢測周期。
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>
工作得很好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.