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]

相关内容

热门资讯

揭秘真相!wepoker有没有... 揭秘真相!wepoker有没有挂,werplan怎么透视,一贯是有挂(有挂助手);在进入软件靠谱后,...
记者发布!wepoker辅助软... 记者发布!wepoker辅助软件价格,红龙poker辅助,其实是真的有挂(有挂存在)1、完成wepo...
最新技巧!hhpoker辅助软... 最新技巧!hhpoker辅助软件,wepoker轻量版透视方法,一直有挂(有人有挂)1)辅助插件:进...
技术分享!云扑克有透视吗,po... 技术分享!云扑克有透视吗,pokemmo脚本,果然是有挂(真是有挂)1、金币登录送、破产送、升级送、...
交流学习经验!德普之星辅助软件... 交流学习经验!德普之星辅助软件,德州透视插件,原来存在有挂(详细教程)1、该软件可以轻松地帮助玩家将...
解密关于!wepoker怎么获... 解密关于!wepoker怎么获得好牌,wpk透视工作室,切实是真的有挂(真实有挂)小薇(辅助器软件下...
记者揭秘!聚星ai辅助工具收费... 记者揭秘!聚星ai辅助工具收费多少,wepokerplus透视脚本免费,总是是真的有挂(有挂详细)1...
一分钟了解!wepoker私人... 一分钟了解!wepoker私人局外卦,werplan脚本,原来真的是有挂(新版有挂)1、首先打开辅助...
必备教程!如何下载德普之星辅助... 必备教程!如何下载德普之星辅助软件,pokemmo辅助脚本,一贯存在有挂(竟然有挂)1、有没有辅助教...
发现一款!wepoker辅助器... 发现一款!wepoker辅助器免费,wepoker插件辅助,好像有挂(确实有挂)所有人都在同一条线上...