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]

相关内容

热门资讯

玩家爆料!约局吧能不能开挂,w... 玩家爆料!约局吧能不能开挂,wepoker透视脚本苹果版,存在挂教程(有挂技巧)是一款可以让一直输的...
必知教程!wepoker底牌透... 必知教程!wepoker底牌透视,wepoker俱乐部辅助,玩家教你(有挂攻略);实战中需综合运用上...
分享一款!德州局怎么透视,智星... 分享一款!德州局怎么透视,智星菠萝透视,wpk教程(有挂透视);大神普及一款德州ai内幕,确定了德州...
交流学习经验!wepoker数... 交流学习经验!wepoker数据分析,德普之星透视辅助软件激活码,扑克教程(有挂辅助)是一款可以让一...
大神推荐!红龙poker辅助器... 大神推荐!红龙poker辅助器免费观看,epoker有透视吗,切实教程(有挂技巧)科技教程也叫必备教...
记者爆料!德扑圈透视,wepo... 记者爆料!德扑圈透视,wepoker辅助脚本,第三方教程(有挂技巧)是一款可以让一直输的玩家,快速成...
科普!wpk辅助软件,hhpo... 科普!wpk辅助软件,hhpoker有没有辅助,攻略教程(有挂技巧)科技教程也叫必备教程,这是一款功...
技术分享!wepoker破解工... 技术分享!wepoker破解工具,wepoker辅助脚本,总结教程(有挂技巧);小薇(透视辅助)致您...
我来教大家!hh poker插... 我来教大家!hh poker插件下载,德普之星怎么开辅助,安装教程(有挂透视);人气非常高,ai更新...
科普!wepoker有没有挂,... 您好,wepoker有没有挂这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很多...