angular - 导航在 Angular 区域外触发,您是否忘记调用 'ngZone.run()' ?

标签 angular angular-router zonejs

我正在使用 Angular 7 并遇到问题 => 在成功登录 API GET 调用并且组件也接收数据后,但 UI 不显示该数据。

当我打开浏览器控制台时,数据会立即填充到 UI 上,并且控制台中会显示一条警告。

"core.js:15686 Navigation triggered outside Angular zone, did you forget to call 'ngZone.run()'?"

我用谷歌搜索了这个警告并找到了一些解决方法,例如 this.ngZone.run() 并在其中调用我的 API。

但问题是,我使用了 40 多个组件,并且在每个组件中调用了如此多的 API。所以我必须在每次 API 调用时调用 ngZone.run(),这似乎很难做到。

克服此问题的更好方法是什么?

app.component.ts

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

app.service.ts

@Injectable()
export class EmployeeService {
    constructor(private httpClient: HttpClient) { }

    getEmployees() {
        return this.httpClient.get<EmployeeModel[]>('employees');
    }

最佳答案

通常,当您将 Angular 调用从与 Angular 代码无关的外部 JavaScript 包装在某些外部 js 回调中时,就会发生这种情况。

示例 app.component.ts:

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

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

在这种情况下,您必须将调用包含在 NgZone 中,例如: this.ngZone.run(() => this.getEmployees());

app.component.ts 将如下所示:

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

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

关于angular - 导航在 Angular 区域外触发,您是否忘记调用 'ngZone.run()' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53645534/

相关文章:

javascript - Three.js ply loader - 对象未正确渲染

angular - 处理事件绑定(bind)中的 EventEmitter 错误

angular - 错误 : Cannot match any routes. URL 段: 'homePage'

Angular2 @输入: Passing an objects array from parent to child component

node.js - 如何在 docker 容器内安装全局 angular-cli?

angular - Angular 路由如何优先于静态站点上的文件路径

angular - 在 Angular 4 中使用 ID 进行路由

javascript - ZoneAwarePromise 已在 Meteor 上被覆盖

javascript - Angular 4 + zonejs : routing stops working after uncaught error

javascript - promise 数组和 Promise.all()