【问题标题】:angular universal destroy moduleref角度通用破坏模块参考
【发布时间】:2017-12-20 03:55:56
【问题描述】:

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

【问题讨论】:

  • 如果删除该行会发生什么?
  • 它会从第一个请求推送渲染的 html,我也会在第一个请求后保存 moduleRef

标签: node.js angular angular-universal


【解决方案1】:

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

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 推送到路由器来使应用程序不稳定(isStable=false)以启动“changeDetector”。但是如果您知道“isStable”是区域的一个属性(每个应用程序一个),并且技巧是在“zone.run(...)”中调用“router.navigateByUrl”来破坏区域的稳定性。 1) 应用程序处理新路由 2) zone 自身不稳定 3)等到稳定(区域内没有任何任务) 4) 渲染 5) 利润!

结果:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-28
    • 1970-01-01
    • 2018-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多