所以我最终在这里使用的解决方案是创建一个StyleStateTransferService
利用@ngx-universal/state-transfer库的。
在服务器端应用程序中,我从头部提取角度样式并将它们添加到状态传输服务中。在客户端应用程序中,我从传输状态中获取样式并将它们添加到头部。Angular 完成引导后,我会检查并删除我添加的那些,这样就不会出现重复项。
我不知道这是否是最好的解决方案,也许有人有更好的解决方案,我最初希望预引导中缺少一些配置,但似乎并非如此。
服务:
@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
// elements have a weird structure on the server
// this filters to style tags with the ng-transition attribute that have content
.filter(el =>
el.name === 'style' && el.attribs['ng-transition'] && el.firstChild && el.firstChild.data)
// extract the css content of the style tags
.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');
// set this attribute so we can remove them later
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) {
// waits until the app has fully initialised before adding the styles to the state
this.appRef.isStable
.filter(isStable => isStable)
.first()
.subscribe(() => {
this.styleStateTransferService.addStylesToState();
});
}
}
export class AppBrowserModule {
constructor(private styleStateTransferService: StyleStateTransferService) {
this.styleStateTransferService.injectStylesFromState();
}
}