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有透视底牌吗,wepoker手机版透视脚本(详细私人局透视)1、在wepok...
透视了解!aapoker辅助怎... 透视了解!aapoker辅助怎么用(透视)aapoker怎么设置提高好牌几率,wpk教程(有挂介绍)...
透视智能ai!wepoker辅... 透视智能ai!wepoker辅助器怎么弄,htx矩阵wepoker辅助(详细手机版辅助)1、任何we...
透视系统!aapoker怎么控... 透视系统!aapoker怎么控制牌(透视)aapoker怎么控制牌,第三方教程(有挂黑科技);aap...
透视能赢!wepoker辅助器... 透视能赢!wepoker辅助器最新版本更新内容,wepoker安装教程(详细辅助软件价格)1、完成w...
透视教程!aapoker怎么控... 透视教程!aapoker怎么控制牌(透视)aapoker怎么提高中牌率,扑克教程(有挂解说);1、点...
透视好友!wepoker私人局... 透视好友!wepoker私人局透视方法,wepokerplus外挂(详细购买模拟器)一、wepoke...
透视游戏!aapoker辅助器... 透视游戏!aapoker辅助器是真的吗(透视)aapoker破解侠是真的吗,可靠教程(有挂细节)在进...
透视美元局!wepoker正确... 透视美元局!wepoker正确养号方法,wepoker正确养号方法(详细可以挂底牌);1、下载好we...
透视攻略!aapoker辅助器... 透视攻略!aapoker辅助器是真的吗(透视)aapoker辅助器是真的吗,必胜教程(有挂细节)小薇...