Angular 服务器端渲染应用一个常见的内存泄漏问题

Angular 服务器端渲染应用一个常见的内存泄漏问题

考虑如下的 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).subscribe(() => {})    );  }  ngOnDestroy(): void {    this.subscription.unsubscribe();  }}

屏幕闪烁问题

用户浏览显示从服务器渲染并返回的页面,一瞬间出现白屏,闪烁片刻,然后应用程序开始运行,看起来一切正常。出现闪烁的原因,在于 Angular 不知道如何重用它在服务器上成功渲染的内容。在客户端环境中,它从根元素中 strip 所有 HTML 并重新开始绘制。

闪烁问题可以抽象成如下步骤

关于正在发生的事情的一个非常简化的解释:

(1) 用户访问应用程序(或刷新)

(2) 服务器在服务器中构建html

(3) 它被发送到用户的浏览器端

(4) Angular 重新创建 应用程序(就好像它是一个常规的非 Angular Universal 程序)

(5) 当上述四个步骤发生时,用户会看到一个 blink 即闪烁的屏幕。

代码如下:

// You can see this by adding:// You should see a console log in the server// `Running on the server with appId=my-app-id`// and then you'll see in the browser console something like// `Running on the browser with appId=my-app-id`export class AppModule {  constructor(    @Inject(PLATFORM_ID) private platformId: Object,    @Inject(APP_ID) private appId: string) {    const platform = isPlatformBrowser(this.platformId) ?      'in the browser' : 'on the server';    console.log(`Running ${platform} with appId=${this.appId}`);  }}

无法通过 API 的方式终止渲染

什么时候需要人为干预的方式终止一个服务器端渲染?

始终明确一点,渲染应用程序的时间点发生在应用程序 applicationRef.isStable 返回 true 时,参考下列代码:

https://github.com/angular/angular/blob/11.1.x/packages/platform-server/src/utils.ts#L43

function _render<T>(    platform: PlatformRef, moduleRefPromise: Promise<NgModuleRef<T>>): Promise<string> {  return moduleRefPromise.then((moduleRef) => {    const transitionId = moduleRef.injector.get(ɵTRANSITION_ID, null);    if (!transitionId) {      throw new Error(          `renderModule[Factory]() requires the use of BrowserModule.withServerTransition() to ensurethe server-rendered app can be properly bootstrapped into a client app.`);    }    const applicationRef: ApplicationRef = moduleRef.injector.get(ApplicationRef);    return applicationRef.isStable.pipe((first((isStable: boolean) => isStable)))        .toPromise()        .then(() => {          const platformState = platform.injector.get(PlatformState);         ...
免责声明:本网信息来自于互联网,目的在于传递更多信息,并不代表本网赞同其观点。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,并请自行核实相关内容。本站不承担此类作品侵权行为的直接责任及连带责任。如若本网有任何内容侵犯您的权益,请及时联系我们,本站将会在24小时内处理完毕。
相关文章
返回顶部