从ngOnInit分派动作时,ExpressionChangedAfterItHasBeenCheckedError

Mar*_* M. 5 rxjs typescript ngrx angular ngrx-store

我正在订阅要ngrx存储在我的构造函数中AppComponent

export class AppComponent {
    submenuItems: Observable<Array<INavigationBarItem>>;

    constructor(private store: Store<AppState>) {
        this.submenuItems = this.store.select<Array<INavigationBarItem>>((state: AppState) => state.submenu.items);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,我在其他组件的ngOnInit方法中调度一个动作,如下所示:

export class SearchPageComponent implements OnInit {
    constructor(private store: Store<AppState>) { }

    ngOnInit(): void {
        this.store.dispatch(new SubmenuAction([
            { title: 'Search', isActive: true },
            { title: 'New Group' }
        ]));
    }
}
Run Code Online (Sandbox Code Playgroud)

这种交互的结果是ExpressionChangedAfterItHasBeenCheckedError例外。如果我将该dispatch调用移至子组件的构造函数,则不会引发任何错误,但是我想知道这是否只是偶然。我也不认为将其放在构造函数体内是一个好主意。

我的每个组件都需要进行此store.dispatch调用-如您所见,它的目的是产生一个子菜单数据,该子菜单数据在页面之间是不同的。如何解决这个异常?

Gia*_*Voß 2

我遇到过这个问题几次,并认为这是 Angular 区域管理的问题。我所做的更像是一个黑客,但也许它也解决了你的问题:

ngOnInit(): void {
    setTimeout(() => this.store.dispatch(new SubmenuAction([
        { title: 'Search', isActive: true },
        { title: 'New Group' }
    ])), 0);
}
Run Code Online (Sandbox Code Playgroud)