在Angular 9中,可以使用Angular Universal来实现服务器端渲染(SSR)。下面是一种解决方法,其中包含了刷新/重载页面的代码示例:
npm install -g @angular/cli
ng add @nguniversal/express-engine
ng new angular-ssr-refresh
cd angular-ssr-refresh
ng generate universal my-universal-app
import { BrowserModule, BrowserTransferStateModule, TransferState } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
@NgModule({
imports: [
BrowserModule.withServerTransition({ appId: 'my-universal-app' }),
BrowserTransferStateModule
],
providers: [TransferState],
bootstrap: [AppComponent]
})
export class AppModule { }
import 'zone.js/dist/zone-node';
import { APP_BASE_HREF } from '@angular/common';
import { ngExpressEngine } from '@nguniversal/express-engine';
import * as express from 'express';
import { join } from 'path';
const app = express();
const PORT = process.env.PORT || 4000;
const DIST_FOLDER = join(process.cwd(), 'dist/my-universal-app/browser');
const routes = [
'/',
'/home',
'/about',
'/contact'
];
app.engine('html', ngExpressEngine({
bootstrap: AppServerModule,
}));
app.set('view engine', 'html');
app.set('views', DIST_FOLDER);
app.use(express.static(DIST_FOLDER, { index: false }));
app.get('*', (req, res) => {
res.render('index', { req, res });
});
routes.forEach(route => {
app.get(route, (req, res) => {
res.render('index', { req, res });
});
});
app.listen(PORT, () => {
console.log(`Node server listening on http://localhost:${PORT}`);
});
"scripts": {
"build:ssr": "npm run build:client-and-server-bundles && npm run compile:server",
"serve:ssr": "node dist/my-universal-app/server/main.js"
}
npm run build:ssr
npm run serve:ssr
现在,当你刷新或重载页面时,Angular应用将在服务器端重新渲染,并发送给浏览器。这样可以改善应用的性能和SEO优化。
请注意,上述代码示例假定你的应用具有几个基本路由(例如'/','/home','/about','/contact')。你需要根据你的实际应用程序进行相应的修改和调整。
上一篇:Angular 9 SSR 构建服务器错误 -- 错误 ReferenceError: document is not defined
下一篇:Angular 9 SSR出现ReferenceError: navigator is not defined错误。