使用“* ngIf”的Component构造函数中的BehaviourSubject订阅会抛出“ExpressionChangedAfterItHasBeenCheckedError”

问题描述 投票:1回答:1

我在AppComponent中拥有完整的UI,如果没有登录,我只想显示登录屏幕。

我创建了一个BehaviourSubject并在AppComponent构造函数中订阅了它。

登录工作正常,但下一次更改(例如注销)引用:

错误: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>

如果没有登录,我只想显示登录屏幕。

angular typescript rxjs
1个回答
0
投票

虽然此错误可被视为警告(它不会在生产模式下显示,并且通常对您的应用程序无害),但有一些方法可以避免这种情况。由于您已使用observable发出loggedIn状态,因此最简单的方法应该是使用异步管道。

尝试将authenticationService设置为public并使用*ngIf="(authenticationService.loggedIn$ | async); else showLoginBox"。无需在组件中存储布尔值。

© www.soinside.com 2019 - 2024. All rights reserved.