问题描述:在 Angular 服务器端渲染时,如果有 lazy loading 模块使用了 Router-outlet,那么在预渲染中,该模块的 HTML 代码会被忽略。
解决方案:需要手动将 lazy loading 模块中的组件添加到预渲染中,或者在使用 Router 懒加载时,使用 preboot.js 库,它可以在预渲染时记录组件状态,并在客户端渲染时重放状态。
这里简单介绍一下如何手动添加组件到预渲染中。
import 'reflect-metadata';
import { APP_BOOTSTRAP_LISTENER, ApplicationRef, CompilerFactory, Inject, Injectable, Injector, ModuleWithProviders, NgModule, Type } from '@angular/core';
import { Compiler } from '@angular/compiler';
import { renderModuleFactory } from '@angular/platform-server';
import { INITIAL_CONFIG, PlatformState } from '@angular/platform-server';
export interface ExtraProvider {
provide: any;
useValue: any;
}
const ADDITIONAL_PROVIDERS: ExtraProvider[] = [];
export function renderModule(
moduleType: Type,
providers: ExtraProvider[] = [],
url: string,
document: string
): Promise {
// Here the magic happens. We take the module, compile it, then
// turn it into a render-aware object. This allows us to do the
// actual rendering of the modules and components that are
// in the dependency chain of the root module.
@NgModule({
imports: [moduleType],
providers: [
...ADDITIONAL_PROVIDERS,
...providers
]
})
class RenderModule {
}
// We bootstrap the app module through a factory, then generate
// the document. The document itself will no longer contain
// , instead it