首页 > 解决方案 > isStable 在角度中的真正含义是什么?

问题描述

在 Angular 中,我们可以使用ApplicationRef Service 获取正在运行的应用程序的引用,然后我们可以将其注入以供进一步使用。在那里,我发现了一个属性isStable,它的定义看起来很简单,但我真的很想了解 Angular 如何认为一个应用程序是稳定的?

定义:

isStable: Observable<boolean>: 只读返回一个指示应用程序何时稳定或不稳定的 Observable。

他们是否检查主堆栈为空并且事件队列为空以将其称为稳定或其他?此外,角度应用程序的引用意味着在浏览器中运行的进程,对吗?

标签: angular

解决方案


源代码作为Angular 存储库ApplicationRef.isStable一部分在 GitHub 上提供。

application_ref.ts

const isStable = new Observable<boolean>((observer: Observer<boolean>) => {
    // Create the subscription to onStable outside the Angular Zone so that
    // the callback is run outside the Angular Zone.
    let stableSub: Subscription;
    this._zone.runOutsideAngular(() => {
        stableSub = this._zone.onStable.subscribe(() => {
        NgZone.assertNotInAngularZone();

        // Check whether there are no pending macro/micro tasks in the next tick
        // to allow for NgZone to update the state.
        scheduleMicroTask(() => {
            if (!this._stable && !this._zone.hasPendingMacrotasks &&
                !this._zone.hasPendingMicrotasks) {
            
                this._stable = true;
                observer.next(true);
            }
        });
    });
});

因此,当一个应用程序的依赖注入区域没有当前或计划的微或宏任务时,它被认为是稳定的。

ng_zone.ts

onHasTask:
    (delegate: ZoneDelegate, current: Zone, target: Zone, hasTaskState: HasTaskState) => {
      delegate.hasTask(target, hasTaskState);
      if (current === target) {
        // We are only interested in hasTask events which originate from our zone
        // (A child hasTask event is not interesting to us)
        if (hasTaskState.change == 'microTask') {
          zone._hasPendingMicrotasks = hasTaskState.microTask;
          updateMicroTaskStatus(zone);
          checkStable(zone);
        } else if (hasTaskState.change == 'macroTask') {
          zone.hasPendingMacrotasks = hasTaskState.macroTask;
        }
      }
    },

推荐阅读