本文介绍了导航在Angular区域之外触发,您是否忘了调用"ngZone.run()"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using Angular 7 and facing an issue => after login the API GET calls successfully and the component receiving data too, but UI is not displaying that data.

当我打开浏览器控制台时,立即将数据填充到UI上,并在控制台中显示警告.

When I open the browser console, immediately the data gets populated on the UI and a warning is showing in the console.

我已经搜索了此警告,并找到了诸如this.ngZone.run()之类的解决方法,并在其中调用了我的API.

I have googled this warning and found some workaround like this.ngZone.run() and call my API's inside it.

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

But the issue is, I am using more than 40 components and calling so many API in each component. So I have to call ngZone.run() on each API call, which seems to be difficult to do.

请向我建议克服此问题的更好方法.预先感谢.

Please suggest me the better approach to overcome this issue.Thanks in advance.

getEmployees(): void {
    this.employeeService.getEmployees().subscribe(e => {
        this.employees = e;
    });
}
@Injectable()
export class EmployeeService {
    constructor(private httpClient: HttpClient) { }

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

推荐答案

通常,当您将角度调用包装在来自与角度代码无关的外部JavaScript的某些外部js回调中时,会发生这种情况.

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

示例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());

In this case you will have to include the call into the NgZone, example: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区域之外触发,您是否忘了调用"ngZone.run()"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 12:11