gpt4 book ai didi

node.js - Angular 通用销毁模块ref

转载 作者:太空宇宙 更新时间:2023-11-04 02:03:34 26 4
gpt4 key购买 nike

是否可以避免破坏 moduleRef 并将其重用于下一个请求(例如在浏览器中工作)?应用程序花费了太多时间来重新填充存储(API 请求),因此我找到了缓存它的可能性。

这里是来自ngx-universal/express-engine的源代码

function handleModuleRef(moduleRef: NgModuleRef<{}>, callback: Function, req, res) {
const state = moduleRef.injector.get(PlatformState);
const appRef = moduleRef.injector.get(ApplicationRef);

appRef.tick();
appRef.isStable
.filter((isStable: boolean) => isStable)
.first()
.subscribe((stable) => {
const bootstrap = moduleRef.instance['ngOnBootstrap'];
bootstrap && bootstrap();

if (!res || !res.finished) callback(null, state.renderToString());
moduleRef.destroy(); // remove this line and avoid creating new instance of NgModuleRef every request
});
}

最佳答案

调试帮助我理解它是如何工作的,我正在实现这样的代码:

function handleModuleRef(moduleRef: NgModuleRef<{}>, callback: Function, req, res) {
const state = moduleRef.injector.get(PlatformState);
const appRef = moduleRef.injector.get(ApplicationRef);
const router = appRef.components[0].instance.router;
const zone = appRef.components[0].instance.zone;
zone.run(() => {
router.navigateByUrl(req.originalUrl);
});
appRef.isStable
.filter((isStable: boolean) => isStable)
.first()
.subscribe((stable) => {
const bootstrap = moduleRef.instance['ngOnBootstrap'];
bootstrap && bootstrap();

if (!res || !res.finished) callback(null, state.renderToString());
});
}

我们需要在引导的主要组件中注入(inject) Router 和 NgZone

当我们进入“handleModuleRef”时,我们需要通过将新的导航 URL 推送到路由器来不稳定(isStable=false)应用程序以启动“changeDetector”。但是,如果您知道“isStable”是区域的一个属性(每个应用程序一个),并且技巧是在“zone.run(...)”内调用“router.navigateByUrl”来破坏区域的稳定。1)应用程序处理新路由2) 区域自身不稳定3)等待稳定(区域内无任务)4)渲染5)利润!

结果:

  • 通过将所有应用程序缓存在内存中并避免每个请求进行引导,渲染速度可提高 2-3-4 倍
  • 可能存在内存泄漏(应用程序在 docker 中启动,如果不小心掉落将会重新启动)
  • 应用的连续状态

关于node.js - Angular 通用销毁模块ref,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45113284/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com