因此,我最终采用的解决方案是创建一个
StyleStateTransferService
,它利用
@ngx-universal/state-transfer库。
在服务器端应用程序中,我从head中获取angular样式并将其添加到状态传输服务中。在客户端应用程序中,我从传输的状态中获取样式并将其添加到head中。一旦Angular完成引导,我就会遍历并删除我添加的样式,以免有重复的样式存在。
我不知道这是否是最好的解决方案,也许有人有更好的解决方案,我最初希望preboot中缺少一些配置,但似乎不是这样。
服务:
@Injectable()
export class StyleStateTransferService {
document: any;
window: Window;
renderer: Renderer2;
ngStyleId = 'ng_styles';
constructor(private stateTransferService: StateTransferService,
@Inject(DOCUMENT) document: any,
private winRef: WindowRef,
private rendererFactory: RendererFactory2) {
this.window = winRef.nativeWindow;
this.document = document;
this.renderer = rendererFactory.createRenderer(this.document, null);
}
addStylesToState() {
const styles: string[] = this.document.head.children
.filter(el =>
el.name === 'style' && el.attribs['ng-transition'] && el.firstChild && el.firstChild.data)
.map(el => el.firstChild.data.replace(/\n/g, ' '));
this.stateTransferService.set(this.ngStyleId, styles);
this.stateTransferService.inject();
}
injectStylesFromState() {
const styles = _.get(this.window, `${DEFAULT_STATE_ID}.${this.ngStyleId}`, []);
styles.forEach(content => {
const styleEl = this.renderer.createElement('style');
this.renderer.setAttribute(styleEl, 'ng-state-transfer', null);
this.renderer.setProperty(styleEl, 'innerHTML', content);
this.renderer.appendChild(this.document.head, styleEl);
});
}
cleanupInjectedStyles() {
Array.from(<HTMLElement[]>this.document.head.children)
.filter(htmlEl => htmlEl.tagName === 'STYLE' && htmlEl.hasAttribute('ng-state-transfer'))
.forEach(styleEl => this.renderer.removeChild(this.document.head, styleEl));
}
在服务器和浏览器模块中使用它(清理操作发生在应用组件中,但似乎不值得展示):
export class AppServerModule {
constructor(private appRef: ApplicationRef,
private styleStateTransferService: StyleStateTransferService) {
this.appRef.isStable
.filter(isStable => isStable)
.first()
.subscribe(() => {
this.styleStateTransferService.addStylesToState();
});
}
}
export class AppBrowserModule {
constructor(private styleStateTransferService: StyleStateTransferService) {
this.styleStateTransferService.injectStylesFromState();
}
}