angular - *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
应该对这些变化做出反应并立即显示一组好的按钮。跳上你的灯来理解这个问题。
解决方案
应该是这样的:
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>
推荐阅读
- r - 如何将变量设置为全局环境中的因子
- asp.net-web-api - 在 .net 框架上使用 Asp.Net Web API 在 Cookie 中传递 JWT
- bamboo - 作为竹变量传递的秘密在 bash 脚本中为空
- django - 您已通过 allaye 身份验证,但无权访问此页面。您想登录其他帐户吗?
- sql-server - T-SQL - 根据来自两个不同列的匹配数据求和数量
- javascript - 如何从 vuejs 访问 application.properties 中定义的变量?
- grails - Grails 4 测试:在同一个 Spock 规范上实现 ServiceUnitTest 和 DataTest
- javascript - 在 TypeScript 中复制地图行为
- react-native - 将 redux-saga 与 @reduxjs/toolkit 一起使用,尝试使用 Provider 但它不起作用。在这种情况下如何使用 Provider
- reactjs - 使用 React 和 Recoil.js 保持 websocket 连接的状态