考虑如下的 Angular 代码:
import { Injectable, NgZone } from "@angular/core";
import { interval } from "rxjs";
@Injectable()
export class LocationService {constructor(ngZone: NgZone) {ngZone.runOutsideAngular(() => interval(1000).subscribe(() => {...}));}
}
这段代码不会影响应用程序的稳定性,但是如果应用程序在服务器上被销毁,传递给订阅的回调将继续被调用。 服务器上应用程序的每次启动都会以 interval 的形式留下一个 artifact.
这是一个潜在的内存泄漏点。
这个内存泄漏风险可以通过使用 ngOnDestoroy 钩子解决。这个钩子适用于 Component 和 service. 我们需要保存 interval 返回的订阅(subscription),并在服务被销毁时终止它。
退订 subscription 的技巧有很多,下面是一个例子:
import { Injectable, NgZone, OnDestroy } from "@angular/core";
import { interval, Subscription } from "rxjs";
@Injectable()
export class LocationService implements OnDestroy {private subscription: Subscription;constructor(ngZone: NgZone) {this.subscription = ngZone.runOutsideAngular(() =>interval(1000).