Igor Simic
3 years ago

Angular router navigate warning - did you forget to call ngZone.run()?




After using Google login button, user needs to be redirected to a different route using router.navigate but Angular does not navigate correctly to that route but throws a warning in console  "Navigation triggered outside Angular zone, did you forget to call 'ngZone.run()'?" and sometimes it can break the design especially if you are using Angular Material.

The reason for this is that route.navigate was called outside Angular zone, and to solve that issue we have to import ngZone to our component from where we are calling route navigation:

import { NgZone } from '@angular/core';
import { AuthService } from '../../../Services/auth-service.service'; // our auth service which will redirect user


export class GoogleLoginComponent implements OnInit {

  constructor(
      private authService:AuthService,
      private ngZone:NgZone
  ) { }

googleLogin(){

    this.GoogleAuth.grantOfflineAccess().then(
        (response) => {

            // this will throe the warning "did you forget to call 'ngZone.run()"
            this.navigateTo('/');

            // but this will work fine
            this.ngZone.run(()=>this.navigateTo('/'));
        },
        (error) => {
             console.log(error);
        });

    }

    navigateTo(url){

       this.router.navigate([url]);

   }

}