#angular #typescript #express #angular-universal #ngx-translate
Вопрос:
Итак, у меня есть приложение Angular 11 с универсальным приложением Angular.
Я использую npm run build:ssr
приложение и npm run serve:serve
для обслуживания.
Корневой путь загружается почти мгновенно, и если я использую навигацию по приложению, он также загружает все пути очень быстро.
Проблема в том, что:
- Когда я вручную ввожу URL-адрес в браузер, например [основной путь]/о программе или [основной путь]/категории, загрузка приложения занимает около 10 секунд. ( этого времени достаточно для тайм-аута сканеров )
/страница о программе-это просто статический компонент с текстом ( с ngx-переводом ) /категории-это лениво загружаемый модуль
{
path: 'about',
component: AboutComponent
},
{
path: 'categories',
loadChildren: () => import('./modules/categories/categories.module').then(m => m.CategoriesModule)
},
Таким образом, проблема, похоже, не связана с ленивой загрузкой.
Я установил @nguniversal/express-engine: "^11.2.1"
Мой сервер.ts :
import 'zone.js/dist/zone-node';
import 'localstorage-polyfill';
import 'reflect-metadata';
import { ngExpressEngine } from '@nguniversal/express-engine';
import * as express from 'express';
import { join } from 'path';
import { AppServerModule } from './src/main.server';
import { APP_BASE_HREF } from '@angular/common';
import { existsSync } from 'fs';
const domino = require('domino');
const fs = require('fs');
const path = require('path');
const template = fs.readFileSync(path.join(join(process.cwd(), 'dist/client/browser'), 'index.html')).toString();
const win = domino.createWindow(template);
global['window'] = win;
global['document'] = win.document;
global['sessionStorage'] = win.sessionStorage;
global['localStorage'] = localStorage;
global['location'] = win.location;
global['navigator'] = win.navigator;
global['WebSocket'] = require('ws');
global['XMLHttpRequest'] = require('xmlhttprequest').XMLHttpRequest;
// The Express app is exported so that it can be used by serverless Functions.
export function app() {
const server = express();
const distFolder = join(process.cwd(), 'dist/client/browser');
const indexHtml = existsSync(join(distFolder, 'index.original.html')) ? 'index.original.html' : 'index';
// Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine)
server.engine('html', ngExpressEngine({
bootstrap: AppServerModule,
}));
server.set('view engine', 'html');
server.set('views', distFolder);
// Example Express Rest API endpoints
// server.get('/api/**', (req, res) => { });
// Serve static files from /browser
server.get('*.*', express.static(distFolder, {
maxAge: '1y'
}));
// All regular routes use the Universal engine
server.get('*', (req, res) => {
res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] });
});
return server;
}
function run() {
const port = process.env.PORT || 4000;
// Start up the Node server
const server = app();
server.listen(port, () => {
console.log(`Node Express server listening on http://localhost:${port}`);
});
}
// Webpack will replace 'require' with '__webpack_require__'
// '__non_webpack_require__' is a proxy to Node 'require'
// The below code is to ensure that the server is run only when not requiring the bundle.
declare const __non_webpack_require__: NodeRequire;
const mainModule = __non_webpack_require__.main;
const moduleFilename = mainModule amp;amp; mainModule.filename || '';
if (moduleFilename === __filename || moduleFilename.includes('iisnode')) {
run();
}
export * from './src/main.server';
приложение.сервер.модуль.ts:
import { NgModule } from '@angular/core';
import {ServerModule, ServerTransferStateModule} from '@angular/platform-server';
import { AppModule } from './app.module';
import { AppComponent } from './app.component';
import {HTTP_INTERCEPTORS} from '@angular/common/http';
import {TranslateInterceptor} from './shared/providers/translate.interceptor';
@NgModule({
imports: [
AppModule,
ServerModule,
ServerTransferStateModule
],
bootstrap: [AppComponent],
providers: [
{provide: HTTP_INTERCEPTORS, useClass: TranslateInterceptor, multi: true}
],
})
export class AppServerModule {}
translate.interceptor.ts
import { REQUEST } from '@nguniversal/express-engine/tokens';
import * as express from 'express';
import { HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Inject, Injectable } from '@angular/core';
@Injectable()
export class TranslateInterceptor implements HttpInterceptor {
private readonly DEFAULT_PORT = 4000; // use 4200 if serving with dev ssr
private readonly PORT = process.env.PORT || this.DEFAULT_PORT;
constructor(@Inject(REQUEST) private request: express.Request) {}
getBaseUrl(req: express.Request) {
const { protocol, hostname } = req;
return this.PORT ?
`${protocol}://${hostname}:${this.PORT}` :
`${protocol}://${hostname}`;
}
intercept(request: HttpRequest<any>, next: HttpHandler) {
if (request.url.startsWith('./assets')) {
const baseUrl = this.getBaseUrl(this.request);
request = request.clone({
url: `${baseUrl}/${request.url.replace('./assets','assets')}`
});
}
return next.handle(request);
}
}
Any help would be appreciated. Im out of ideas..