首页 > 解决方案 > ngIf 中的 ExpressionChangedAfterItHasBeenCheckedError?

问题描述

我无法弄清楚我在这里缺少什么。

共享服务A:

export class SharedServiceA {
    somethingWasUpdated = new Subject();

    updateSomething(value) {
        this.somethingWasUpdated.next(value);
    }
}

另一个服务:

export class AnotherService {
    doSomething() {
        this.sharedServiceA.updateSomething(true);
    }
}

组件-a.component.ts

export class ComponentA {
    list = [];
    isShowList = false;

    ngOnInit() {
        this.sharedServiceA.somethingWasUpdated
            .pipe(takeUntil(this.destroyed))
            .subscribe(
                data => {
                    if (data) {
                        this.fetchData(); // Get data from another service, then populate list
                    }
                }
            );
    }
    
    fetchData() {
        // Get data from another service
        if (dataFound) {
            this.list = dataFound;
            this.isShowList = true;
        } else {
            this.isShowList = false;
        }
    }
}

组件-a.component.html

<div *ngIf="!isShowList"> <!-- This is where ExpressionChangedAfterItHasBeenCheckedError points to: Previous value: 'ngIf: true'. Current value: 'ngIf: false' -->
    List empty
</div>
<div *ngIf="isShowList">
    Print something here
</div>

组件-b.component.html

export class ComponentB {
    ngOnInit() {
        this.sharedServiceA.somethingWasUpdated
            .pipe(takeUntil(this.destroyed))
            .subscribe(
                data => {
                    if (data) {
                        // Get data from another service
                    }
                }
            );

        this.anotherService.doSomething(); // If I place this inside a setTimeout, I don't get the ExpressionChangedAfterItHasBeenCheckedError
    }
}

这是场景:

  1. 单击一个按钮 >ComponentA在选项卡内创建

  2. 单击另一个按钮 >ComponentB在另一个选项卡中创建(基本上与 并排ComponentA)> ComponentA.fetchData()> ExpressionChangedAfterItHasBeenCheckedError

为什么我会在被填充并设置为之后得到一个ExpressionChangedAfterItHasBeenCheckedErrorin ,如果我放在a中,为什么我不会收到错误消息?ComponentAlistisShowListtruethis.anotherService.doSomething();setTimeout

此代码如何违反单向数据流?即使在阅读了几篇文章之后,我仍然对这种特殊情况感到困惑。

标签: javascriptangular

解决方案


快速点,ExpressionChangedAfterItHasBeenChecked 错误仅在开发模式下可见。不要在生产模式下显示。


推荐阅读