angular - 使用“*ngIf”的组件构造函数中的 BehaviourSubject 订阅会引发“ExpressionChangedAfterItHasBeenCheckedError”
问题描述
我在 AppComponent 中有完整的 UI,如果未登录,我只想显示登录屏幕。
我创建了一个 BehaviourSubject 并在 AppComponent 构造函数中订阅了它。
登录有效,但下一个更改(例如注销)参考:
ERROR 错误:ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后已更改。以前的值:'ngIf: true'。当前值:'ngIf: false'。
app.component.ts
export class AppComponent implements OnInit {
isLoggedIn = false;
constructor(private authenticationService: AuthenticationService) {
this.authenticationService.loggedIn$.subscribe((res) => {
this.isLoggedIn = res;
});
}
ngOnInit(): void {
}
}
app.component.html
<div *ngIf="isLoggedIn; else showLoginBox">
<div class="container-fluid d-flex">
<div id="main-content">
<router-outlet></router-outlet>
</div>
</div>
</div>
<ng-template #showLoginBox>
<app-login></app-login>
</ng-template>
如果未登录,我只想显示登录屏幕。
解决方案
虽然这个错误可以被视为一个警告(它不会在生产模式下显示,并且通常对您的应用程序无害),但有一些方法可以避免这种情况。由于您已经使用 observable 来发出已登录状态,因此最简单的方法应该是使用异步管道。
尝试公开 authenticationService 并使用*ngIf="(authenticationService.loggedIn$ | async); else showLoginBox"
. 无需将布尔值存储在您的组件中。
推荐阅读
- node.js - Node.js 应用选择嵌套的 JSON 列
- javascript - Expo - iOS SKStoreReviewController.requestReview() 在企业版本中不起作用
- android - 在android上使用数据绑定覆盖布局
- sorting - 要在 O(n) 中排序的 N 个整数?
- java - 以编程方式将解析图像和文本加载到线性布局中
- perl - 为什么 $_ 在单个替换和全局替换之间没有变化
- python - Django - ForeignKey“反向”(“_set”)
- javascript - Javascript 和 SharePoint 2013:为列表项设置背景颜色
- node.js - 是否可以在 Alexa Skill 中放置单独的导出功能?
- javascript - 如何解析为图像内容类型:从服务器接收的图像/bmp?