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]

相关内容

热门资讯

一分钟快速了解!hhpoker... 一分钟快速了解!hhpoker的辅助是真的吗,拱趴大菠萝万能挂,解说技巧(其实真的是有挂)-哔哩哔哩...
今日公布!wepoker线上大... 今日公布!wepoker线上大神,wepoker怎么看底牌,规律教程(一贯有挂)-哔哩哔哩;wepo...
透视游戏!hhpoker德州透... 透视游戏!hhpoker德州透视挂,wepoker透视破解版,攻略教程!(其实是有挂的)-哔哩哔哩;...
总算清楚!wepoker开辅助... 总算清楚!wepoker开辅助能查到吗,wepokerplus脚本,wepoke教程(一直是有挂的)...
透视苹果版!aapoker透视... 透视苹果版!aapoker透视脚本入口,hhpoker透视方法,AI教程(果然真的是有挂)-哔哩哔哩...
玩家必备教程!wepoker永... 玩家必备教程!wepoker永久免费脚本,聚星ai辅助工具下载,揭秘攻略(其实真的有挂)-哔哩哔哩;...
玩家必知教程!wejoker辅... 玩家必知教程!wejoker辅助软件视频,aapoker能控制牌吗,详细教程!(果然是有挂的)-哔哩...
热门推荐!werplan怎么透... 【福星临门,好运相随】;热门推荐!werplan怎么透视,德州之星扫描器,2026新版技巧(一直真的...
一分钟揭秘!wepokerpl... 一分钟揭秘!wepokerplus辅助,hh poker辅助器先试用,揭秘攻略(一贯是有挂的)-哔哩...
终于清楚!newpoker怎么... 终于清楚!newpoker怎么安装脚本,we-poker软件,力荐教程(一直是有挂的)-哔哩哔哩;1...