I'm new in the Angular I'm trying to make a interceptor spinner for http requests,
but only I have an ExpressionChangedAfterItHasBeenCheckedError
error.
This errors appears when i opening a modal window for create something, and this component making a http request.
The debugger marks an error inside spinner component
<ng-container *ngIf="loading$ | async">
<mat-progress-bar mode="indeterminate"></mat-progress-bar>
Error can be resolved by writing a delay(0)
but I don’t think it’s good
export class SpinnerComponent implements OnInit {
loading$;
constructor(private spinnerService: SpinnerService) { }
ngOnInit() {
this.loading$ = this.spinnerService.isLoading$
.pipe(
delay(0)
);
}
}
=====
Spinner Interceptor
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
import { SpinnerService } from './spinner.service';
import { finalize } from 'rxjs/operators';
@Injectable()
export class SpinnerInterceptor implements HttpInterceptor {
requestCount = 0;
constructor(private spinnerService: SpinnerService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.requestCount++;
this.spinnerService.show();
return next.handle(request)
.pipe(
finalize(() => {
this.requestCount--;
if (this.requestCount === 0) {
this.spinnerService.hide();
}
})
);
}
}
=====
Spinner Service
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class SpinnerService {
isLoading$ = new Subject<boolean>();
show() {
this.isLoading$.next(true);
}
hide() {
this.isLoading$.next(false);
}
}
=====
Spinner Component
import { Component, OnInit } from '@angular/core';
import { SpinnerService } from '../services/spinner.service';
import { Subject } from 'rxjs';
@Component({
selector: 'app-spinner',
templateUrl: './spinner.component.html',
styleUrls: ['./spinner.component.scss']
})
export class SpinnerComponent implements OnInit {
loading$: Subject<boolean> = this.spinnerService.isLoading$;
constructor(private spinnerService: SpinnerService) { }
ngOnInit() {}
}
I absolutely can not understand how to solve it, and because of what it appears