简体   繁体   English

角度4 ExpressionChangedAfterItHaHasBeenCheckedError具有可观察到的但不能保证

[英]Angular 4 ExpressionChangedAfterItHasBeenCheckedError with observable but not promise

I am experiencing this error when a child component sets text in another component through a shared service. 当子组件通过共享服务在另一个组件中设置文本时,我遇到此错误。 This happens when the child component subscribes to an Observable from the Angular Translation service in its onInit hook. 当子组件在其onInit挂钩中从Angular Translation服务预订了Observable时,就会发生这种情况。 However, if I change the observable to a promise ( .toPromise().then(..) over .subscribe(..) , the problem vanishes. 但是,如果我将可观察对象更改为一个承诺对象( .toPromise().then(..)不是.subscribe(..) ,则问题将消失。

I would like to understand why. 我想知道为什么。

My setup... 我的设定...

root.component.html: root.component.html:

<app-page-title>{{ 'STRINGS.loading' | translate }}</app-page-title>
<div>
  <!-- view component rendered here -->
  <router-outlet (activate)='onActivate($event)'></router-outlet>
</div>

page-title.service.ts: page-title.service.ts:

getPageTitle() {
  return this.pageTitle;
}
setPageTitle(pageTitle: string) {
  this.pageTitle = pageTitle;
}

page-title.component.html: page-title.component.html:

<div>
  <div *ngIf="isBack()">
    <div class="page-title-text">
     {{getPageTitle()}}
    </div>
  ...
  </div>
</div>

view.component.ts: view.component.ts:

ngOnInit() {
  // Triggers ExpressionChangedAfterItHasBeenCheckedError 
  this.translationService.get('VIEW.title').subscribe(pageTitle => this.titleService.setPageTitle(pageTitle));

  // Works
  // this.translationService.get('VIEW.title').toPromise().then(pageTitle => this.titleService.setPageTitle(pageTitle));

}

One other thing to note is, this is a SPA. 要注意的另一件事是,这是SPA。 The error only shows up when loading the view.component through javascript by navigating to it through the app. 仅当通过javascript通过应用程序导航到view.component加载view.component时,才会显示该错误。 If on the view where this problem presents itself, and I hit refresh, the error does not occur. 如果在出现此问题的视图上,并且我单击了刷新,则不会发生该错误。

I've read a little bit about this behavior here: https://blog.angularindepth.com/everything-you-need-to-know-about-the-expressionchangedafterithasbeencheckederror-error-e3fd9ce7dbb4 我已经在这里阅读了有关此行为的一些信息: https : //blog.angularindepth.com/everything-you-need-to-know-about-the-expressionchangedafterithasbeencheckederror-error-e3fd9ce7dbb4

but I still do not understand why this problem is occurring specifically with an Observable, but not a promise. 但是我仍然不明白为什么这个问题是由于Observable而不是诺言而发生的。

view.component.ts view.component.ts

ngOnInit() {
   this.translationService.get('VIEW.title').subscribe(pageTitle => 
     setTimeout(() => {
       this.titleService.setPageTitle(pageTitle);
     }, 0);
   );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM