I'm integrating a loading indicator for my project, the visibility of which will be determined centrally in a HTTP Interceptor service. However, after implementing, I received the following error:
ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'null'. Current value: 'true'.
Below are my stripped down files:
app.component.ts
import { SpinnerService } from '@app/services/spinner.service';
import { Subject } from 'rxjs';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnDestroy {
title = 'My App';
isLoading: Subject<boolean> = this.spinnerService.isLoading;
constructor(public spinnerService: SpinnerService) {
}
}
app.component.html
<div class="example-container" [class.example-is-mobile]="mobileQuery.matches">
<router-outlet></router-outlet>
<div *ngIf="isLoading | async" class="overlay">
Loading
</div>
</div>
spinner.service.ts
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable()
export class SpinnerService {
isLoading = new Subject<boolean>();
constructor() {
}
show() {
this.isLoading.next(true);
}
hide() {
this.isLoading.next(false);
}
}
interceptor.service.ts
import { Injectable } from '@angular/core';
import {HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpErrorResponse} from '@angular/common/http';
import {EMPTY, Observable, throwError} from 'rxjs';
import { environment } from '@env/environment';
import { finalize } from 'rxjs/operators';
import { SpinnerService } from '@app/services/spinner.service';
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
// snackBar: MatSnackBar;
constructor(public spinnerService: SpinnerService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.spinnerService.show();
return next.handle(request).pipe(
finalize(() => this.spinnerService.hide()),
);
}
}
and finally example usage is below in my other components:
this.http.get(`${environment.apiUrl}/form/schema/days`)
.subscribe(data => {
console.log('done', data);
});
I can't figure out what I could be doing wrong here, could someone shed some more light on it?