2

我最近将我的 Angular 项目更新到版本 9。我正在使用一项服务来更新主菜单的标题,它运行成功,但现在生成了这个错误:

core.js:5828 ERROR 错误: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或生产时没有错误。

4

2 回答 2

1

我在 ngOnInit 中调用了“setTitle”函数。从构造函数调用它解决了这个问题。

不在生产模式下时会出错:

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

这解决了问题:

constructor(
  private mainService: MainService
) {
  this.mainService.setTitle('My title');
}
于 2020-02-17T06:58:38.787 回答
1

如果在从路由中获取 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.
  }

}

于 2021-01-16T13:10:53.180 回答