首页 > 解决方案 > 如何在 Angular 区域外调用 HttpClient?

问题描述

在我的应用程序中,我需要在页面加载时调用慢速 API 端点。此调用不会真正影响应用程序,但应在页面加载时立即执行。

在执行请求的整个过程中,队列中有一个宏任务可以防止 Angular Zone 变得稳定和不可测试(在 e2e-tests 中)。

这是我唯一需要被 Zone 忽略的事情,所有其他的都应该像往常一样等待,许多测试已经依赖它。所以waitForAngularEnabled在测试中关闭并不是最好的选择。

我试图在 Angular Zone 之外执行这个持久的调用,如下所示:

this.ngZone.runOutsideAngular(() => this.httpClient.post(...))

XMLHttpRequest任务仍在队列中并阻塞了区域稳定性: 区域任务

请告知在 Angular Zone 之外运行 Http 请求的方法是什么?

标签: angularxmlhttprequestzone

解决方案


这是我用来完全忽略区域中的 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


推荐阅读