Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'Navigation triggered outside Angular zone' explanation

I am working on an Electron app using Angular. I have created an Electron menu item where click() sends an IPC to app.component.ts in order to change the view. The below code works, but I get the following error in DevTools if I call router.navigateByUrl directly:

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

As you can see, I now call router.navigateByUrl through ngZone, solving the problem, but despite reading about NgZone in the docs and searching here and elsewhere, I don't understand what this does or why I need to do it.

  1. What's wrong with calling this.router.navigateByUrl directly?

  2. Why does it tell me the call is outside the Angular zone, when it is called within app.component.ts?

Electron main.js

function sendToAngularRouter(request)
{
    console.log('sending request');
    win.webContents.send('routeToPage', request);
}

Angular app.component.ts

export class AppComponent implements OnInit {

    constructor(public electronService: ElectronService, 
         private router: Router, private zone: NgZone) {}

    ngOnInit() {
        this.electronService.ipcRenderer.on('routeToPage', (sender, arg) => {
          this.navigateTo(arg);
        });
    }

    navigateTo(arg: string): void {
        this.zone.run(() => {
            this.router.navigateByUrl(`/${arg}`);
        });
    }
}

Thank you in advance.

like image 893
Kezz Avatar asked Jan 30 '19 21:01

Kezz


People also ask

What is the use of NgZone?

A zone is an execution context that persists across async tasks. You can think of it as thread-local storage for the JavaScript VM. This guide describes how to use Angular's NgZone to automatically detect changes in the component to update HTML.

What is the purpose of zone dependency in Angular project?

Angular uses the zone to patch async APIs(addEventListener, setTimeout(), ...) and uses notifications from these patched APIs to run change detection every time some async event happened. Also zonejs is useful for debugging, testing, profiling. It helps you see whole call stack if you face with some error.

What is Zone Evergreen?

Evergreen, Colorado is in USDA Hardiness Zones 5a and 5b.


1 Answers

As the documentation says:

A zone provides an execution context that persists across async tasks

The navigation is an async task, and angular needs to detect the change across electron to render your new View, so the angular zone, defines what is running into the angular execution context, and what is running outside, in this case electron

like image 154
Luis Fernando Hernandez Avatar answered Sep 27 '22 21:09

Luis Fernando Hernandez