Home > Mobile >  Angular async routing function outside ngZone
Angular async routing function outside ngZone

Time:10-24

The routing function was called in a service. I'm getting this warning:

Navigation triggered outside Angular zone, did you forget to call 'ngZone.run()'?

However I can not call this.ngZone.run(...) because I need the event when the routing was completed. By default ngZone.run() => void does not return any value.

The function looks like this:

private handleRedirectRouting(): Observable<boolean> {
   return this.route.queryParamMap.pipe(
      switchMap((params) => {
         if (params.get('_redirect')) {
            const route = params.get('_redirect');
            return from(this.router.navigate([route]));
         } else if (this.router.url.includes('auth/login')) {
            const route = '/';
            return from(this.router.navigate([route]));
         }
         return of(true);
      })
   );
}

How can I resolve it?

CodePudding user response:

ngZone.run() is the right thing here since it can return a promise.

from(this.ngZone.run(() => {
   return this.router.navigate([route]));
}))

CodePudding user response:

I could resolve the code error by explicitly passing the return type of the function call:

this.ngZone.run<Observable<boolean>>(() => {
   return from(this.router.navigate([route]));
})
  • Related