Search code examples
angularasynchronousservicerxjs

Getting ExpressionChangedAfterItHasBeenCheckedError


Getting ExpressionChangedAfterItHasBeenCheckedError when using a component in multiple place who subscribe a behaviour object for loading. Error occurs when component is loaded in one component and try to load or destroy in another component.

@Component({
template: 'common.component.html',
selector: 'app-common'
})

export CommonComponent implements OnInit{

constructor(service: MyService){}

ngOnInit(){
}

}

**common.component.html**

<div>
    <div *ngIf="service.isLoading$ | async">Loading...</div>
</div>


**component 1**

<div>
    <app-common></app-common>
</div>

component 2

<div>
    <app-common></app-common>
</div>


@Injectable()
export class MyService {
  public isLoading = new BehaviorSubject<any>(false);
  public isLoading$ = this.isLoading.asObservable();
}```

Solution

  • public isLoading$ = this.isLoading.asObservable().pipe(delay(0))
    

    more about it

    https://blog.angular-university.io/angular-debugging/