当使用Angular Universal时,页面加载两次的问题通常出现在首次渲染时。下面是一种解决方法,可以避免页面加载两次的问题:
import { Component, ChangeDetectionStrategy } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class AppComponent {
// ...
}
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule, NoopAnimationsModule } from '@angular/platform-browser/animations';
@NgModule({
imports: [
BrowserModule.withServerTransition({ appId: 'serverApp' }),
// BrowserAnimationsModule, // 注释掉
NoopAnimationsModule // 添加
],
// ...
})
export class AppModule { }
import { renderModule } from '@angular/platform-server';
// ...
app.get('*', (req, res) => {
// ...
const indexHtml = fs.readFileSync(indexHtmlPath, 'utf-8');
const renderedHtml = indexHtml.replace('{{SSR_CONTENT}}', '');
// res.send(renderedHtml); // 注释掉
renderModule(AppServerModule, { document: renderedHtml }).then(html => {
res.send(html);
});
});
这些步骤可以解决Angular Universal页面加载两次的问题。请注意,这只是其中一种解决方法,具体解决方法可能因项目设置而有所不同。