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]

相关内容

热门资讯

透视普及!德扑之心免费透视(透... 透视普及!德扑之心免费透视(透视)哈糖大菠萝挂,教程秘籍(有挂教程)-哔哩哔哩1、下载好德扑之心免费...
透视透视!hhpoker辅助软... 透视透视!hhpoker辅助软件下载(透视)hhpoker真的有透视吗,教程方案(了解有挂)-哔哩哔...
透视有挂!hhpoker德州透... 透视有挂!hhpoker德州透视(透视)hhpoker透视工具,教程方针(有挂秘笈)-哔哩哔哩在进入...
透视教你!hhpoker俱乐部... 透视教你!hhpoker俱乐部是干嘛的(透视)德普辅助软件,教程阶段(真实有挂)-哔哩哔哩1、点击下...
透视详情!德州hhpoker是... 透视详情!德州hhpoker是真的吗(透视)aa poker辅助包,教程操作(有挂教学)-哔哩哔哩1...
透视揭露!newpoker脚本... 透视揭露!newpoker脚本(透视)聚星ai辅助工具激活码,教程技法(有挂教程)-哔哩哔哩1)聚星...
透视详情!菠萝德普辅助器免费版... 透视详情!菠萝德普辅助器免费版在哪里(透视)wepoker私人局透视插件,教程教材(有挂教学)-哔哩...
透视开挂!we-poker有人... 透视开挂!we-poker有人玩吗(透视)pokemmo脚本,教程练习(有挂细节)-哔哩哔哩1、we...
透视揭幕!wpk系统是否存在透... 透视揭幕!wpk系统是否存在透视行为(透视)wpk德州局怎么透视,教程策略(有挂教程)-哔哩哔哩该软...
透视辅助!epoker透视(透... 透视辅助!epoker透视(透视)约局吧开挂,教程举措(新版有挂)-哔哩哔哩该软件可以轻松地帮助玩家...