在 angular 中,我们可以使用 ApplicationRef 服务获取正在运行的应用程序的引用,然后我们可以注入该服务以供进一步使用。在那里,我发现了一个属性 isStable,它的定义看起来很简单,但我真的想了解 Angular 如何将一个应用程序视为稳定的?
定义:
<块引用>isStable: Observable<boolean>
: Read-Only 返回一个 Observable
指示应用程序何时稳定或不稳定。
他们是否检查主堆栈为空并且事件队列为空以调用它稳定或其他什么?另外,angular 应用的引用意味着在浏览器中运行的进程,对吗?
答案 0 :(得分:1)
ApplicationRef.isStable
源代码作为 Angular repository 的一部分在 GitHub 上提供。
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);
}
});
});
});
因此,当应用程序的依赖注入区没有当前或计划的微或宏任务时,应用程序被认为是稳定的。
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;
}
}
},