S
S
stepa902020-05-21 12:18:52
Angular
stepa90, 2020-05-21 12:18:52

How to fix ExpressionChangedAfterItHasBeenCheckedError when using router.events and navigate?

Implemented a transition spinner between child components using router.events.
Main Component Template

<div [ngClass]="{'loading-class':loading}">
<router-outlet></router-outlet>
</div>


The component itself

export class MyComponent {
    loading: boolean;
    constructor(router: Router) {
        router.events
            .pipe(
                filter(e => e instanceof NavigationStart || e instanceof NavigationEnd),
                map(e => e instanceof NavigationStart),
                distinctUntilChanged()
            )
            .subscribe(loading => this.loading = loading);
    }
}

As a result, NavigateStart shows the loading wheel, and NavigateEnd shows the page.
Everything works great, but if we navigate to the same router (url) where we are, for example when we need to clear the parameters in the url, an ExpressionChangedAfterItHasBeenCheckedError occurs because we have already initialized the component .

Google only helped to find crutch solutions - make the change asynchronous (setTimeout or EventEmitter(true)) or force a change of environment. This article describes them and also says that such solutions are bad.

I myself came up with only remembering the url when navigating and then checking it with a new one during transitions, but this is also a hack.
Perhaps there is a more elegant solution. I'm sure someone has already experienced this.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Shvets, 2020-05-21
@stepa90

export class MyComponent {
  loadingClass = this.createLoadingClass();

  constructor(router: Router) {}

  private createLoadingClass(): Observable<boolean> {
    return router.events.pipe(
      map(e => e instanceof NavigationStart),
    );
  }
}

<div [class.loading]="loadingClass | async">
But why is this needed? Why does it take so long to navigate the route?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question