【问题标题】:Angular SSR - using performance.now() in both browser and serverAngular SSR - 在浏览器和服务器中使用 performance.now()
【发布时间】:2021-09-09 00:08:55
【问题描述】:

我想在我的 Angular 组件中设置一些性能标记和度量,以衡量所选组件处理和渲染所需的时间。在“客户端模式”下运行应用程序时它们工作正常,但是一旦我在 SSR 模式下运行应用程序,我就会得到“性能”未定义。

我尝试从节点“perf_hooks”内部模块导入它,但是当从 app.component.ts 调用时,我得到了未知模块“perf_hooks”。
https://github.com/buggy1985/angular-ssr-performance/blob/HEAD/src/app/app.component.ts#L17

如果我在 server.ts 中使用 performance.now(),它似乎可以正常工作。 https://github.com/buggy1985/angular-ssr-performance/blob/HEAD/server.ts#L13

我可以将性能类从 server.ts 传递给组件吗?并且浏览器回退到window.performance?还是我做错了什么?

【问题讨论】:

  • 您可以将调用包装在仅在浏览器上运行的条件中
  • 我也想在服务器模式下使用它们。我应该能够在服务器上使用节点内部模块并在浏览器中使用 window.performance
  • 看起来,您应该为服务器端创建自己的实现。我还没有做过类似的事情,但我相信这是可能的。

标签: angular performance node-modules angular-universal browser-api


【解决方案1】:

我终于设法通过根据平台提供正确的性能 api 来解决它。

这是我所做更改的完整提交: https://github.com/buggy1985/angular-ssr-performance/commit/39aa08489e589172fa9bce6f1f5588f5eb962337

我基本上创建了一个新的提供程序,它从 server.ts 中的 perf_hooks 注入导入的性能

import { performance } from 'perf_hooks';
export const PERFORMANCE_API = new InjectionToken('performance-api');
...

@NgModule({
  providers: [
    { provide: PERFORMANCE_API, useValue: performance },
  ],
}

并在 app.browser.module 中注入 windows.performance

providers: [
  { provide: PERFORMANCE_API, useValue: window.performance },
],

在app.component.ts中,不是直接使用性能,而是要在构造函数中注入,然后作为this.performance使用。

constructor(@Inject(PERFORMANCE_API) private performance) {
    console.log(this.performance.now());
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-01
    • 1970-01-01
    • 2019-10-27
    • 2015-11-16
    • 1970-01-01
    • 2013-01-22
    • 1970-01-01
    相关资源
    最近更新 更多