如果Angular 2+ Universal页面在服务器上不渲染,可能是由于以下几个原因引起的:
// server.ts
import 'zone.js/dist/zone-node';
import 'reflect-metadata';
import { enableProdMode } from '@angular/core';
import { ngExpressEngine } from '@nguniversal/express-engine';
import * as express from 'express';
import { join } from 'path';
import { AppServerModule } from './src/main.server';
enableProdMode();
const app = express();
const PORT = process.env.PORT || 4000;
const DIST_FOLDER = join(process.cwd(), 'dist/browser');
app.engine('html', ngExpressEngine({
bootstrap: AppServerModule
}));
app.set('view engine', 'html');
app.set('views', DIST_FOLDER);
app.get('*.*', express.static(DIST_FOLDER, {
maxAge: '1y'
}));
app.get('*', (req, res) => {
res.render('index', { req });
});
app.listen(PORT, () => {
console.log(`Node server listening on http://localhost:${PORT}`);
});
BrowserModule.withServerTransition
方法来配置服务器端渲染。以下是一个示例:// app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ServerModule, ServerTransferStateModule } from '@angular/platform-server';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
import { AppModule } from './app.module';
@NgModule({
imports: [
BrowserModule.withServerTransition({ appId: 'my-app' }),
BrowserAnimationsModule,
ServerModule,
ServerTransferStateModule,
HttpClientModule,
AppModule
],
bootstrap: [AppComponent]
})
export class AppServerModule { }
isPlatformServer
和TransferState
等API来处理服务器端和客户端之间的数据传递。以下是一个示例:import { Component, Inject, PLATFORM_ID } from '@angular/core';
import { isPlatformServer, TransferState } from '@angular/platform-browser';
@Component({
selector: 'app-root',
template: `
{{ title }}
{{ message }}
`
})
export class AppComponent {
title: string;
message: string;
constructor(
private transferState: TransferState,
@Inject(PLATFORM_ID) private platformId: Object
) {
this.title = 'Angular Universal';
this.message = this.transferState.get('message', '');
if (isPlatformServer(this.platformId)) {
// 在服务器端设置消息
this.transferState.set('message', 'This message is rendered on the server');
}
}
}
通过确保正确配置服务器端渲染、AppModule和使用Angular Universal的API,您应该能够解决Angular 2+ Universal页面在服务器上不渲染的问题。