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

时光总嘲笑我的痴心妄想 提交于 2019-12-03 01:14:50

Usually this happens when you are wrapping angular calls inside some external js callback, from external JavaScript not related to angular code.

Example app.component.ts:

callMyCustomJsLibrary() {
  googleSdk.getLocations(location => this.getEmployees());
}

getEmployees(): void {
    this.employeeService.getEmployees().subscribe(e => {
        this.employees = e;
    });
}

In this case you will have to include the call into the NgZone, example: this.ngZone.run(() => this.getEmployees());

The app.component.ts would then look like the following:

callMyCustomJsLibrary() {
  googleSdk.getLocations(location => this.ngZone.run(() => this.getEmployees()));
}

getEmployees(): void {
    this.employeeService.getEmployees().subscribe(e => {
        this.employees = e;
    });
}

If i talk from top then meaning of the this warning is that event is trigger outside of zone i.e. if you know about zones or also called execution context which angular is used for change detection and UI rendering. so while navigration it is expected by the angular to re renderer the UI but it is not happening here that's the problem you are facing. so it throw this warning because angular process the change detection and UI rendering when the code executed lies inside of angular zone.

But actually This warning comes when you trying to call the router navigration inside the subscribe method.

Put your router navigation call outside of subscribe method and it will not throw this warning again. and you will see the expected UI after navigation.

for more info about zones read and watch the video mention below:-

https://blog.thoughtram.io/angular/2017/02/21/using-zones-in-angular-for-better-performance.html#running-outside-angulars-zone

https://www.youtube.com/watch?v=3IqtmUscE_U&t=150

This happens if you try injecting a custom made service:

constructor(private myService: MyService) {
}

while you forgot to provide it in the module configuration:

@NgModule({
  providers: [
    MyService
  ]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!