考虑如下的 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 时,参考下列代码:
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 ensure
the 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);
...到此这篇关于angular 服务器端渲染应用一个常见的内存泄漏问题的文章就介绍到这了,更多相关angular内存泄漏内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论