簡體   English   中英

ExpressionChangedAfterItHasBeenCheckedError 在更新到 Angular 9 后,在啟用 Ivy 時從子項更改父屬性

[英]ExpressionChangedAfterItHasBeenCheckedError after updating to Angular 9 on changing parent property from the child when Ivy is enabled

我最近將我的 Angular 項目更新到版本 9。我正在使用一項服務來更新主菜單的 header,它工作成功但現在生成此錯誤:

core.js:5828 錯誤錯誤:ExpressionChangedAfterItHasBeenCheckedError:檢查后表達式已更改。 先前的值:'主標題'。 當前值:“新標題”。

每次標題更改時都會出現此錯誤。

這是我的代碼的一部分:

我的路由:

應用程序路由.module.ts:

const routes: Routes = [
  {
    path: '',
    component: MainComponent,
    canActivate: [AuthGuard],
    canActivateChild: [AuthGuard],

    children: [
      {
        path: '',
        component: DashboardComponent
      },
      {
        path: 'warehouse',
        loadChildren: () =>
          import('./systems/warehouse/warehouse.module').then(
            m => m.WarehouseModule
          )
      },
      {
        path: 'commerce',
        loadChildren: () =>
          import('./systems/commerce/commerce.module').then(
            m => m.CommerceModule
          )
      },
      {
...

主要成分:

main.component.ts:

  pageTitle: string;

  ngOnInit() {
    this.mainService.pageTitle$.subscribe((title: string) => {
      this.pageTitle = title;
    });
...

我用來更改標題的服務: main.service.ts:

  public setTitle(title: string) {
    this.pageTitle$.emit(title);
  }

最后,我的一位客戶在倉庫模塊中更改了標題:

main.service.ts:

this.mainService.setTitle('new title');

更新:

問題發生在 Ivy 啟用並處於開發模式時。 "enableIvy": false或生產時沒有錯誤。

我在 ngOnInit 中調用 'setTitle' function。 從構造函數中調用它解決了問題。

這在不處於生產模式時會出錯:

ngOnInit() {
    this.mainService.setTitle('My title');
}

這解決了問題:

constructor(
  private mainService: MainService
) {
  this.mainService.setTitle('My title');
}

如果從路由中獲取 Params 后必須更改標題怎么辦。 因此,您必須在 ngOnInitMethod 中使用 setTitle 方法。 它給出了一個錯誤。

為了防止這種情況,我向 AppComponent 添加了一個更改檢測器:

export class AppComponent implements OnInit, AfterContentChecked {

  constructor(public title: Title, private cdr: ChangeDetectorRef,) {
    this.titl.setHeaderTitle('Home');
  }

  ngAfterContentChecked() {
    this.cdr.detectChanges(); // It fixes but can lead to performance issues.
  }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM