1

I'm trying to add a loading spinner on each http.get action in my app.

Here is my http.get :

protected get(url: string): any {

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

The SessionServicecall my LoadingService :

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

}

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

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

here is my service 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);
  }

}   

Then, here is a part of my main layout component :

  showLoadingDiv : boolean;

  constructor(public loadingService : LoadingService) { 
  }

  ngOnInit() {

  }


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

And finally, in my Html layout template :

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

When others modules are load fast, I do not have the error ExpressionChangedAfterItHasBeenCheckedError but If a module take a little time (because huge data), I've got this error.

I'm already see this SO but not work for me : https://stackoverflow.com/a/38846793/1729211

Portekoi
  • 1,087
  • 2
  • 22
  • 44

1 Answers1

0

The error occurs when changing the value in the ngAfterViewInit life cycle hook. The quick way to fix it would be wrapping the code in your .subscribe in setTimeout(). There was a good article that explained this in depth but I can't find it on my phone, perhaps someone else can post it.

Christian
  • 2,676
  • 3
  • 15
  • 25
  • I don't like the timeout solution because it depend of the response of others servers. The only solution I found is using `[class.hidden]="!showLoadingDiv"`. If I use `[ngClass]="showLoadingDiv?'show':'hidden'"`, I get the error. Same with `*ngIf="showLoadingDiv"` – Portekoi Nov 01 '17 at 16:00
  • Another Solution could be to call the ChangeDetection yourself in the subscribe by injecting `ChangeDetectorRef` into your constructor and calling `detectChanges` inside your subscribe – Chris Nov 27 '17 at 07:25