angular - Angular SSR - 在浏览器和服务器中使用 performance.now()
问题描述
我想在我的 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?或者我做错了什么?
解决方案
我终于设法通过根据平台提供正确的性能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());
}
推荐阅读
- android - Android Studio(3.5.3(stable) win10) 卡在参考资源文件上
- java - 如何向用户发送“无回复”电子邮件?
- mysql - mysql条件根据特定条件验证数据
- python - hsv[...,1] = 255 是什么意思?
- java - 将 jboss 迁移到 tomcat - javax.naming.NamingException
- reactjs - 有没有办法在字符串文本中呈现动态组件
- asp.net - Blazor (.Net core 3.1) 部分类是否等同于`@inject ViewModel`?
- python - 当 Flask 应用程序服务器与应用程序所需的其他文件一起放置在文件夹中时,出现“未找到服务器上未找到请求的 URL”
- python-3.x - 在 CentOS6 中运行 python 子进程和 Libreoffice 6.2 时无法打开显示错误
- html - Open local files and web files in HTML