ExpressionChangedAfterItHasBeenCheckedError。角度2(5)* ngIf

时间:2017-11-20 13:48:09

标签: javascript angularjs angularjs-ng-if

我正在使用服务在子级和父级之间传递数据,目的是根据子级的具体信息更新父级ui。

服务:

import { Subject } from "rxjs/Subject";

export class ChildDataService {
  private childDetails = new Subject<{}>();

  childLoaded$ = this.childDetails.asObservable();
  changedComponentName(option: {}){
    this.childDetails.next(option);
  }
}

父组件:

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { ChildDataService } from "../core/helpers/child-data.service";
import { Subscription } from "rxjs/Subscription";

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class ParentComponent implements OnInit {
  childDetails: {title?: string};

  private subscription:Subscription;

  constructor( private childDataService: ChildDataService) {
    this.childDataService.childLoaded$.subscribe(
      newChildDetails => {
        console.log(newChildDetails);
        this.childDetails = newChildDetails
      });
  }
}

子组件示例:

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { ChildDataService } from "../../core/helpers/child-data.service";

@Component({
  selector: 'app-child-dashboard',
  templateUrl: './child-dashboard.component.html',
  styleUrls: ['./child-dashboard.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class ChildDashboardComponent implements OnInit {

  constructor(private childDataService: ChildDataService) { }

  public ngOnInit() {
    this.childDataService.changedComponentName({
      title: 'Dashboard'
    });
  }
}

父HTML:

<div class="subheader">
  <h1>{{ childDetails?.title }}</h1>
  <button *ngIf="childDetails?.title == 'Dashboard'">dashboard</button>
  <button *ngIf="childDetails?.title == 'SecondChild'">Second Child</button>
</div>

使用此设置,当我点击routerLink时,我收到错误“ExpressionChangedAfterItHasBeenCheckedError”,现在如果我第二次点击同一链接,错误仍然存​​在,但正确的按钮变为可见。花了整个周末无处可去,所以任何帮助都会非常感激。

1 个答案:

答案 0 :(得分:0)

public ngOnInit() {
    setTimeout(() => {
        this.childDataService.changedComponentName({
          title: 'Dashboard'
        }), {});
}

它应该有用。

async ngOnInit() {
   await this.childDataService.changedComponentName({
            title: 'Dashboard'
         });
}
相关问题