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]

相关内容

热门资讯

一分钟法门!佛手在线是不是有挂... 一分钟法门!佛手在线是不是有挂(透视)确实存在有辅助工具(哔哩哔哩)该软件可以轻松地帮助玩家将佛手在...
四分钟插件!潮友会鱼虾蟹有没有... 四分钟插件!潮友会鱼虾蟹有没有挂辅助,新蜜瓜大厅控制器(都是真的有辅助app)-哔哩哔哩四分钟插件!...
九分钟攻略!wpk软件是真的吗... 九分钟攻略!wpk软件是真的吗(透视)好像存在有辅助下载(哔哩哔哩)1、许多玩家不知道wpk软件是真...
六分钟辅助!越乡游辅助器,决战... 六分钟辅助!越乡游辅助器,决战卡五星辅助修改器(确实真的有辅助神器)-哔哩哔哩1、让任何用户在无需决...
6分钟机巧!wepoker透视... 6分钟机巧!wepoker透视挂底牌(透视)原来是有辅助辅助(哔哩哔哩)1、完成wepoker透视挂...
第八分钟脚本!丽水茶苑脚本,奇... 第八分钟脚本!丽水茶苑脚本,奇迹免费自动挂机脚本(一直真的有辅助辅助器)-哔哩哔哩1、这是跨平台的奇...
第九分钟课程!约局吧德州真的存... 第九分钟课程!约局吧德州真的存在透视吗(透视)果然是真的有辅助开挂(哔哩哔哩)该软件可以轻松地帮助玩...
第9分钟辅助!小娴辅助软件下载... 第9分钟辅助!小娴辅助软件下载,欢乐茶馆脚本(其实真的是有辅助神器)-哔哩哔哩第9分钟辅助!小娴辅助...
9分钟指南书!智星菠萝透视(透... 9分钟指南书!智星菠萝透视(透视)都是有辅助工具(哔哩哔哩)暗藏猫腻,小编详细说明智星菠萝透视破解器...
第二分钟脚本!雀友会广东潮汕麻... 第二分钟脚本!雀友会广东潮汕麻雀有挂么,518互游辅助(果然真的是有辅助下载)-哔哩哔哩运雀友会广东...