【问题标题】:ExpressionChangedAfterItHasBeenCheckedError after updating to Angular 9 on changing parent property from the child when Ivy is enabledExpressionChangedAfterItHasBeenCheckedError 在启用 Ivy 时更新到 Angular 9 后更改子项的父属性
【发布时间】:2020-02-12 04:22:17
【问题描述】:

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

core.js:5828 ERROR 错误:ExpressionChangedAfterItHasBeenCheckedError: 检查后表达式已更改。以前的值: '主题'。当前值:“新标题”。

每次标题更改时都会出现此错误。

这是我的代码的一部分:

我的路线:

app-routing.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
          )
      },
      {
...

主要成分:

ma​​in.component.ts:

  pageTitle: string;

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

我用来更改标题的服务: ma​​in.service.ts:

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

最后是我在仓库模块中更改标题的客户之一:

ma​​in.service.ts:

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

更新:

该问题仅在启用 Ivy 并处于开发模式时发生。 "enableIvy": false 或生产时没有错误。

【问题讨论】:

  • 如果可能的话,您能否在 stackblitz.com 中重现此问题
  • 如何使用 Angular 9 启动 Stackblits?
  • 你可以在 package.json "@angular/animations": "^8.2.14", "@angular/common": "9.0.0-rc.1", "@angular/compiler": "9.0.0-rc.1", "@angular/core": "9.0.0-rc.1", "@angular/forms": "9.0.0-rc.1", "@angular/platform-browser": "9.0.0-rc.1", "@angular/platform-browser-dynamic": "9.0.0-rc.1", "@angular/router": "9.0.0-rc.1"987654325@替换下面的行
  • 什么是 pageTitle$?是 EventEmitter 吗?
  • @Rajat 是的。是的。

标签: javascript angular angular9


【解决方案1】:

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

这在不处于生产模式时会出错:

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

这解决了问题:

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

【讨论】:

  • 如果从路由中获取Params后必须更改标题怎么办。因此,您必须在ngOnInitMethod 中使用 setTitle 方法。它给出了一个错误。
【解决方案2】:

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

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-07
    • 1970-01-01
    • 2018-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多