繁体   English   中英

角度通用销毁模块

[英]angular universal destroy moduleref

是否有可能避免破坏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());
        });
}

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

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

结果:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM