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、不需要AI权限,帮助你快...
玩家必用!wpk辅助挂多功能透... 玩家必用!wpk辅助挂多功能透视工具,总是是有挂(有挂秘笈)1.wpk 选牌创建新账号,点击进入游戏...
今日头条!德扑之星辅助挂多功能... 今日头条!德扑之星辅助挂多功能透视工具,真是是真的有挂(有挂猫腻)1、德扑之星模拟器是什么优化,德扑...
重大消息!德普之星辅助挂多功能... 重大消息!德普之星辅助挂多功能透视工具,原来存在有挂(有挂头条)1、德普之星免费脚本咨询教程、德普之...
重大消息!wpk辅助挂多功能透... 重大消息!wpk辅助挂多功能透视工具,确实真的是有挂(有挂技术)1、游戏颠覆性的策略玩法,独创攻略技...
解密关于!wepoker辅助挂... 解密关于!wepoker辅助挂多功能透视工具,一贯是真的有挂(有挂规律)1、wepoker辅助器安装...
发现玩家!AAPoKer辅助挂... 发现玩家!AAPoKer辅助挂多功能透视工具,总是是真的有挂(存在有挂)1)AAPoKer辅助插件:...
解密关于!AAPoKer辅助挂... 解密关于!AAPoKer辅助挂多功能透视工具,竟然存在有挂(有挂教程)1、实时AAPoKer透视辅助...
关于!微扑克辅助挂多功能透视工... 关于!微扑克辅助挂多功能透视工具,一贯有挂(有挂详细)1、操作简单,无需微扑克手机版透视脚本,只需要...
揭秘一下!微扑克辅助挂多功能透... 揭秘一下!微扑克辅助挂多功能透视工具,果然是有挂(有挂讲解)1、微扑克模拟器是什么优化,微扑克俱乐部...