Issue
I created a component loading and an interceptor for all requests in my application, loading appears on the screen until the request is finalized. However, I get an error whenever the component of my router outlet changes. can you help me?
My error:
ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: ‘undefined’. Current value: ‘true’. It seems like the view has been created after its parent and its children have been dirty checked. Has it been created in a change detection hook?
My code:
export class MasterPageComponent implements OnInit {
constructor(private el: ElementService, private loader: LoaderService) { }
ngOnInit(): void {}
isLoading: Subject<boolean> = this.loader.isLoading;
}
Master-Page.component.html
<div class="wrapper default-theme" [ngClass]="getClasses()">
<app-navbar></app-navbar>
<main>
<app-sidebar></app-sidebar>
<div class="pages container-fluid pt-4 pb-4 pl-4 pr-4 ">
<router-outlet></router-outlet>
</div>
<div class="overlay" (click)="toggleSidebar()"></div>
</main>
</div>
<app-loading *ngIf="isLoading | async"></app-loading>
My LoaderService:
export class LoaderService {
isLoading = new Subject<boolean>();
show() {
this.isLoading.next(true);
}
hide() {
this.isLoading.next(false);
}
}
My loader interceptor:
export class LoaderInterceptor implements HttpInterceptor {
constructor(private loader: LoaderService) {
}
intercept(req: HttpRequest<any>, next: HttpHandler) {
this.loader.show()
return next.handle(req).pipe(
finalize(() => this.loader.hide())
);
}
}
Solution
It’s not an error, it’s an annoying warning that disappears after you compile your app in --prod
mode.
To silence it :
constructor(private changeDetector : ChangeDetectorRef) { }
ngAfterViewChecked(){
this.changeDetector.detectChanges();
}