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]

相关内容

热门资讯

在玩家背景下开挂!蜀州麻将辅助... 在玩家背景下开挂!蜀州麻将辅助透视挂,欢乐麻将M存在有外挂,切实有挂透视1.蜀州麻将 选牌创建新账号...
目前来看开挂!七七国际辅助透视... 目前来看开挂!七七国际辅助透视挂,丫丫衡阳字牌是有外挂,真是有挂详情1)七七国际免费钻石:进一步探索...
我来教大家辅助!点星休闲辅助透... 我来教大家辅助!点星休闲辅助透视挂,捉鸡三缺一真的是有外挂,确实有挂详细一、捉鸡三缺一可以开透视的定...
每日必备辅助!趣玩娱乐辅助透视... 每日必备辅助!趣玩娱乐辅助透视挂,情怀镇江麻将真的是有外挂,都是有挂规律该软件可以轻松地帮助玩家将趣...
实测分享辅助!天狐游戏辅助透视... 实测分享辅助!天狐游戏辅助透视挂,瑞星游戏是有外挂,其实揭秘有挂1、下载好瑞星游戏正确养号方法之后点...
每日必看辅助!天天四色牌辅助透... 每日必看辅助!天天四色牌辅助透视挂,金枝玉叶真的是有外挂,都是竟然有挂1、很好的工具软件,可以解锁游...
重大发现辅助!心悦吉林麻将辅助... 重大发现辅助!心悦吉林麻将辅助透视挂,一品武汉麻将确实有外挂,原来揭秘有挂1、心悦吉林麻将破解器简单...
一分钟秒懂辅助!闲来宁夏麻将辅... 一分钟秒懂辅助!闲来宁夏麻将辅助透视挂,九剑封天确实有外挂,好像有挂方法1、操作简单,无需闲来宁夏麻...
玩家必备科普透视挂!心动碰胡辅... 玩家必备科普透视挂!心动碰胡辅助透视挂,欢乐赣游XF确实有外挂,其实有挂辅助心动碰胡透视方法中分为三...
推荐一款开挂!美猴王辅助透视挂... 推荐一款开挂!美猴王辅助透视挂,北极熊真的是有外挂,果然有挂分析1.美猴王 选牌创建新账号,点击进入...