我有一个 Angular 16 应用程序,它会在应用程序启动时选择随机背景图像,其工作原理如下:
export class AppComponent implements OnInit {
private readonly backgroundImagesCount = 8;
constructor(@Inject(DOCUMENT) private readonly document: Document) {}
ngOnInit(): void {
const randomNum = Math.floor(Math.random() * this.backgroundImagesCount + 1);
this.document.body.style.backgroundImage = `url('/assets/bg${randomNum}.jpg')`;
}
}
我刚刚将 Angular Universal 添加到此应用程序中,以便它可以预渲染路线。问题是“随机”背景现在被硬编码到预渲染的 HTML 中。当应用程序启动时,您将短暂地看到预先选择的“随机”背景闪烁,然后实际的 Angular 应用程序 Bootstrap 和真正的随机背景被选择。
如何检测应用程序中的预渲染?理想情况下,我想在预渲染时跳过这个 BG 图像内容,但允许它在应用程序引导后运行。有什么我可以使用的东西可以像下面的伪代码一样工作吗?
if(!isPrerendering){
const randomNum = Math.floor(Math.random() * this.backgroundImagesCount + 1);
this.document.body.style.backgroundImage = `url('/assets/bg${randomNum}.jpg')`;
}
最佳答案
您可以使用@Inject(PLATFORM_ID) platformId跳过执行部分代码
使用 @angular/common 包中的 isPlatformServer()
方法检查代码当前是否在服务器端运行。
if (isPlatformServer(platformId)) { .... 跳过设置背景图像 }
关于angular - 如何检测 Angular Universal 预渲染版本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76712956/