AngularUniversalSSR中使用withServerTransition时,ViewEncapsulation无法从服务器传输到浏览器
创始人
2024-10-29 21:01:17
0

在 Angular 中,ViewEncapsulation 控制着在组件中使用的样式是否会被应用到全局 CSS 中。当使用 Angular Universal SSR 时,如果使用 withServerTransition 方法,则组件中的样式将无法在服务器端传输到浏览器,并在渲染时丢失。

解决该问题的方法是使用 TransferState(传输状态)。该服务允许在服务器端缓存数据以便稍后在客户端上使用。在本例中,我们可以将组件中的 ViewEncapsulation 值存储在 TransferState 中,并将其在浏览器中重新设置。以下是具体实现方法。

1.在组件中,使用以下代码将 ViewEncapsulation 值存储在 TransferState 中:

import { Component, Inject, PLATFORM_ID, ViewEncapsulation } from '@angular/core'; import { TransferState, makeStateKey } from '@angular/platform-browser'; import { isPlatformServer } from '@angular/common';

const VIEW_ENCAPSULATION_KEY = makeStateKey('VIEW_ENCAPSULATION');

@Component({ selector: 'app-my-component', templateUrl: './my-component.component.html', styleUrls: ['./my-component.component.scss'], encapsulation: ViewEncapsulation.Emulated // or ViewEncapsulation.None if you want to disable it }) export class MyComponent implements OnInit {

constructor( private transferState: TransferState, @Inject(PLATFORM_ID) private platformId: Object ) { }

ngOnInit() { const viewEncapsulation = this.encapsulationType(); // returns 'Emulated' or 'None' if (isPlatformServer(this.platformId)) { this.transferState.set(VIEW_ENCAPSULATION_KEY, viewEncapsulation); } else { const fromServer = this.transferState.get(VIEW_ENCAPSULATION_KEY, viewEncapsulation); this.encapsulationType(fromServer); } }

private encapsulationType(type?: string): string { if (type) { this.encapsulation = type === 'None' ? ViewEncapsulation.None : ViewEncapsulation.Emulated; } return this.encapsulation === ViewEncapsulation.None ? 'None' : 'Emulated'; }

}

2.在 app.module.ts 文件中,在 BrowserModule 的 imports 数组中添加 BrowserTransferStateModule:

import { BrowserModule, BrowserTransferStateModule } from '@angular/platform-browser';

@NgModule({ imports: [ BrowserModule.withServerTransition({ appId: 'my-app' }), BrowserTransferStateModule ], bootstrap: [AppComponent]

相关内容

热门资讯

教学辅助挂!wpk辅助是什么,... 教学辅助挂!wpk辅助是什么,德普之星私人局辅助免费,其实真的有挂(有挂详情)1、金币登录送、破产送...
我来教教大家!闲聚鱼虾蟹软件脚... 我来教教大家!闲聚鱼虾蟹软件脚本,小程序河北微乐脚本,详细脚本(有挂细节)小程序河北微乐脚本能透视中...
这一现象值得深思!约局吧游戏挂... 这一现象值得深思!约局吧游戏挂,德扑之星透视辅助插件,总是是真的有挂(详细教程)1)德扑之星透视辅助...
玩家必看科普!情怀莆仙外挂,微... 玩家必看科普!情怀莆仙外挂,微信小程序多功能辅助,详细技巧(有挂规律)1、进入游戏-大厅左侧-新手福...
据统计!wepoker透视挂底... 据统计!wepoker透视挂底牌,德普之星透视辅助软件,真是确实有挂(有挂解惑)德普之星透视辅助软件...
一分钟带你了解!情怀国粹麻将神... 一分钟带你了解!情怀国粹麻将神器,皮皮衡阳字牌黑科技视频,详细神器(揭秘有挂)1、在皮皮衡阳字牌黑科...
今年以来!wepoker安装教... 今年以来!wepoker安装教程,德普之星透视辅助软件,好像是真的有挂(有挂头条)1、进入到德普之星...
分享给玩家!泉州相约十三水辅助... 分享给玩家!泉州相约十三水辅助,上饶打炸漏洞,详细教程(有挂总结)1、泉州相约十三水辅助脚本辅助下载...
分享给玩家!温州茶苑破解版,情... 分享给玩家!温州茶苑破解版,情怀四川辅助哪里可以装,详细器(确实有挂)所有人都在同一条线上,像星星一...
据通报!德普之星透视软件免费入... 据通报!德普之星透视软件免费入口官网,智星菠萝辅助,真是真的有挂(有挂教学)1、德普之星透视软件免费...