使用 Ngrx 的 ExpressionChangedAfterItHasBeenCheckedError

Jos*_*lla 5 rxjs redux ngrx angular

我知道这可能会遇到几次,但我找不到干净有效的方法来解决它。我有一段这样的代码 <div *ngIf="userUsername$ | async as username"></div>,当我运行时我得到这个

错误 错误:ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后已更改。以前的值:'ngIf:[对象对象]'。当前值:'ngIf:admin'。

在我的 component.ts 中 userUsername$ = this.store.pipe(select(selectSelectedUsername));

有没有什么有效的方法来解决这个问题而不是setTimeout

谢谢你,

更新

根据要求提供整个组件的代码

import { Component, OnInit, ChangeDetectorRef, ChangeDetectionStrategy, OnDestroy } from '@angular/core';
import { select, Store } from '@ngrx/store';
import { selectSelectedUsername } from '../state-management/selectors/user.selector';
import { IAppState } from '../state-management/state/app.state';

@Component({
  selector: 'my-layout',
  templateUrl: './layout.component.html',
  styleUrls: ['./layout.component.sass']
})
export class LayoutComponent implements OnInit, OnDestroy {

  userUsername$ = this.store.pipe(select(selectSelectedUsername));

  constructor(
    private store: Store<IAppState>
  ) {
  }

  ngOnInit() { }

  ngOnDestroy() { }

}

Run Code Online (Sandbox Code Playgroud)

Pra*_*ani -1

如果你想解决这个错误,那么你可以使用这个

import {ChangeDetectorRef } from '@angular/core';

  constructor(
    title: Title,
    private cdr: ChangeDetectorRef){ }


 this.cdr.detectChanges();
Run Code Online (Sandbox Code Playgroud)

注意:****在您的变量值更改为使用此行后

this.cdr.detectChanges();
Run Code Online (Sandbox Code Playgroud)