angular - 如何在 Angular 区域外调用 HttpClient?
问题描述
在我的应用程序中,我需要在页面加载时调用慢速 API 端点。此调用不会真正影响应用程序,但应在页面加载时立即执行。
在执行请求的整个过程中,队列中有一个宏任务可以防止 Angular Zone 变得稳定和不可测试(在 e2e-tests 中)。
这是我唯一需要被 Zone 忽略的事情,所有其他的都应该像往常一样等待,许多测试已经依赖它。所以waitForAngularEnabled
在测试中关闭并不是最好的选择。
我试图在 Angular Zone 之外执行这个持久的调用,如下所示:
this.ngZone.runOutsideAngular(() => this.httpClient.post(...))
该XMLHttpRequest
任务仍在队列中并阻塞了区域稳定性:
请告知在 Angular Zone 之外运行 Http 请求的方法是什么?
解决方案
这是我用来完全忽略区域中的 XHR 的配置:
(window as any).__zone_symbol__UNPATCHED_EVENTS = [
// mouse and pointer events - the presence of these here can break angular material tooltips
'mouseover', 'mousemove', 'mouseout', 'scroll', 'mousewheel', 'pointerover',
// XHR related events
'load', 'mouseleave', 'readystatechange', 'loadend', 'loadstart', 'progress'];
(window as any).__Zone_disable_requestAnimationFrame = true;
(window as any).__Zone_enable_cross_context_check = true;
(window as any).__Zone_disable_IE_check = true;
(window as any).__Zone_disable_XHR = true;
// The creator of Zone also suggest ignoring properties directly on XHR
// https://github.com/angular/zone.js/issues/1146
(window as any).__Zone_ignore_on_properties = [
{
target: XMLHttpRequest.prototype,
ignoreProperties: ['load', 'readystatechange', 'loadstart', 'loadend', 'progress']
}
];
还要确保这不是直接在 polyfills.ts 中,而是在包含的文件中(在 Angular 8 中,polyfills.ts 中的 zonejs“侦听”事件列表不起作用)
我基于这个问题内的讨论: https ://github.com/angular/zone.js/issues/1146
推荐阅读
- python - 我需要在 python 中制作一个数字拼写游戏程序
- linux - 将 docker 容器连接到互联网
- unetstack - 如何在模拟中以正交割草机模式进行测量的连接2-UAV的节点(USV)动态计算路径?
- android - PDFView 无法从 TabLayout 和 ViewPager2 中的流中加载数据
- r - 如何通过循环在R中保存多个图?
- google-cloud-platform - GCP 数据融合 Azure blob 存储配置 传输多个文件
- arduino - Arduino Tinkercad 气体检测系统压电三阀
- javascript - 使用正则表达式测试字符串匹配只接受 1 和点但 11 不可接受
- mongodb - 发布数据未在 mongodb 集群中发生
- python - 无法降低多层感知器中的训练损失