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]

相关内容

热门资讯

德州微扑克辅助!德扑软件高端,... 德州微扑克辅助!德扑软件高端,云扑克德州都是是有挂(详细ai人工智能教程)(1)德州微扑克辅助!德扑...
wepoke辅助技巧!wepo... wepoke辅助技巧!wepoke软件透明挂,wepower让系统发好牌,科技教程(有挂工具)科技教...
微扑克ai辅助!wPk的确真的... 微扑克ai辅助!wPk的确真的有挂,WPK果然真的有挂,攻略方法(有挂详情)1、微扑克系统规律教程、...
智星德州菠萝有挂吗!wpk胜利... 智星德州菠萝有挂吗!wpk胜利跟号有关,德扑之星ai代打(详细辅助挂教程)1、每一步都需要思考,不同...
德扑起手牌胜率图!德州之星辅助... 德扑起手牌胜率图!德州之星辅助透视,wepower德州都是有挂(详细数据软件教程)1、每一步都需要思...
wepokeai代打的胜率!w... wepokeai代打的胜率!wepokeai代打,wepoke有挂 网上,必备教程(有挂解说),亲,...
wpk德州透视辅助(Wpk)w... wpk德州透视辅助(Wpk)wpk透视辅助合作(透视)就是真的有挂(曝光教程);1、超多福利:超高返...
WePoKe外 挂!wepok... WePoKe外 挂!wepoke美元局稳,aapoker能玩(详细透视教程);(需添加指定薇7574...
德州微扑克辅助!德州ai机器人... 德州微扑克辅助!德州ai机器人软件开发,德扑之星一贯存在有挂(详细有外 挂教程)1、德州微扑克辅助a...
wepoke有辅助挂!wopo... wepoke有辅助挂!wopoker辅助软件(透视)WEpoke(一直真的有挂)1、点击下载安装,微...