【问题标题】:ExpressionChangedAfterItHasBeenCheckedError on Loading Service加载服务时的 ExpressionChangedAfterItHasBeenCheckedError
【发布时间】:2018-04-12 21:06:09
【问题描述】:

我正在尝试在我的应用中的每个 http.get 操作上添加一个加载微调器。

这是我的 http.get :

protected get(url: string): any {

    //Loading start
    this.sessionService.showLoader();
    (...)
}

SessionServicecall 我的LoadingService

constructor(private cookieService: CookieService, private  loadingService : LoadingService) {

}

public showLoader(): void {
    this.loadingService.show();
}

public hideLoader(): void {
    this.loadingService.hide();
}

这是我的服务LoadingService

import { Injectable, OnInit, EventEmitter } from '@angular/core';

@Injectable()
export class LoadingService implements OnInit {


  public loadingEvent: EventEmitter<boolean>;


  constructor() {
    this.loadingEvent = new EventEmitter();
  }

  ngOnInit() {
    this.loadingEvent.emit(false);
  }


  show() {
    this.loadingEvent.emit(true);

  }

  hide() {
    this.loadingEvent.emit(false);
  }

}   

然后,这是我的主要布局组件的一部分:

  showLoadingDiv : boolean;

  constructor(public loadingService : LoadingService) { 
  }

  ngOnInit() {

  }


  ngAfterViewInit(){
    this.loadingService.loadingEvent.subscribe((res) => { 
      this.showLoadingDiv = res;
    });
  }

最后,在我的 Html 布局模板中:

<div class="loaddiv" *ngIf="showLoadingDiv">
 Loading...
</div>

当其他模块快速加载时,我没有错误ExpressionChangedAfterItHasBeenCheckedError,但是如果一个模块需要一点时间(因为数据量很大),我就会遇到这个错误。

我已经看到了这个,但对我不起作用: https://stackoverflow.com/a/38846793/1729211

【问题讨论】:

    标签: angular


    【解决方案1】:

    在 ngAfterViewInit 生命周期钩子中更改值时发生错误。修复它的快速方法是将代码包装在 setTimeout() 中的 .subscribe 中。有一篇很好的文章对此进行了深入的解释,但我在手机上找不到它,也许其他人可以发布它。

    【讨论】:

    • 我不喜欢超时解决方案,因为它取决于其他服务器的响应。我找到的唯一解决方案是使用[class.hidden]="!showLoadingDiv"。如果我使用[ngClass]="showLoadingDiv?'show':'hidden'",我会收到错误消息。与*ngIf="showLoadingDiv" 相同
    • 另一种解决方案可能是通过将ChangeDetectorRef 注入您的构造函数并在您的订阅中调用detectChanges 在订阅中自己调用ChangeDetection
    猜你喜欢
    • 2018-04-17
    • 2021-06-12
    • 1970-01-01
    • 1970-01-01
    • 2014-03-10
    • 2019-01-06
    • 2017-10-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多