Angular服务器端渲染:懒加载页面的Router-outlet没有渲染HTML
创始人
2024-10-25 00:32:08
0次

问题描述:在 Angular 服务器端渲染时,如果有 lazy loading 模块使用了 Router-outlet,那么在预渲染中,该模块的 HTML 代码会被忽略。

解决方案:需要手动将 lazy loading 模块中的组件添加到预渲染中,或者在使用 Router 懒加载时,使用 preboot.js 库,它可以在预渲染时记录组件状态,并在客户端渲染时重放状态。

这里简单介绍一下如何手动添加组件到预渲染中。

  1. 首先需要创建一些工具函数,它们将会处理组件的预渲染和解除预渲染。
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

相关内容

热门资讯

前端-session、jwt 目录:   (1)session (2&#x...
linux入门---制作进度条 了解缓冲区 我们首先来看看下面的操作: 我们首先创建了一个文件并在这个文件里面添加了...
关于测试,我发现了哪些新大陆 关于测试 平常也只是听说过一些关于测试的术语,但并没有使用过测试工具。偶然看到编程老师...
前缀和与对数器与二分法 1. 前缀和 假设有一个数组,我们想大量频繁的去访问L到R这个区间的和,...
nodejs:本地安装nvm实... 一、背景-使用不同版本node的原因 vue3+ts、nuxt3版本,node...
JAVA集合知识整理 Java集合知识整理 HashMap相关 HashMap的底层数据结构:jdk1.8之...
无刷直流电机介绍及单片机控制实... 无刷直流电机介绍及单片机控制实例前言基本概念优势与劣势使用寿命基本结构使用单片机控制实例电子调速器&...
fwdiary(2) dp2 1.传纸条  AcWing 275. 传纸条 - AcWing 走两条路,走一条最大的...
常用的DOS命令 常用的DOS命令 DOS(Disk Operating System,磁...
<C++> 类和对象(下) 1.const成员函数将const修饰的“成员函数”称之为const成员函数,cons...