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]

相关内容

热门资讯

5分钟详情!雀友会潮汕麻将老是... 5分钟详情!雀友会潮汕麻将老是输,wepower透视辅助(详细透视辅助脚本教程);免费雀友会潮汕麻将...
4分钟技巧!四人斗地主有猫腻吗... 4分钟技巧!四人斗地主有猫腻吗,德扑之星是有机制(详细透视辅助软件教程);超受欢迎的四人斗地主有猫腻...
五分钟技巧!欢乐麻将插件iOS... 大家肯定在之前欢乐麻将插件iOS在哪下载或者欢乐麻将插件iOS在哪下载中玩过五分钟技巧!欢乐麻将插件...
1分钟攻略!jj麻将有没有挂,... 1分钟攻略!jj麻将有没有挂,云扑克辅助器是真是假(详细透视辅助助手教程);亲,其实确实真的有挂(需...
2分钟介绍!兴动互娱游戏辅助器... 2分钟介绍!兴动互娱游戏辅助器怎么用,wpk辅助实时策略建议(详细透视辅助挂教程);(需添加指定薇7...
一分钟教学!掌心麻将软挂神器,... WePoker透视辅助版本稳定性对比与推荐‌:一分钟教学!掌心麻将软挂神器,wepoke好友助力(详...
十分钟技巧!科乐长春麻将有挂吗... 十分钟技巧!科乐长春麻将有挂吗,aa扑克能用模拟器(详细透视辅助软件教程);亲,其实确实真的有挂(需...
七分钟了解!海南麻将琼瑶有挂吗... 七分钟了解!海南麻将琼瑶有挂吗,好运大菠萝有辅助(详细透视辅助app教程),支持语音通讯、好友开房及...
4分钟透明!白金岛三打哈怎么拿... 白金岛三打哈怎么拿好牌新手教程相关信息汇总(需添加指定薇757446909获取下载链接);4分钟透明...
4分钟教学!衡阳字牌免费辅助器... 4分钟教学!衡阳字牌免费辅助器,hm3德州辅助(详细透视辅助挂教程)关于衡阳字牌免费辅助器机制的,其...