此问题通常是由于缺少Angular Universal的配置或忽略了将子页面的HTML包含在主HTML中而导致。可以根据以下步骤尝试解决此问题:
"server": { "builder": "@angular/platform-server:server", "options": { "outputPath": "dist/server", "main": "src/main.server.ts", "tsConfig": "src/tsconfig.server.json" } }
2.在app.module.ts中引入BrowserModule和ServerModule,配置app.module.ts以使用Angular Universal并将其导出。例如:
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { ServerModule } from '@angular/platform-server'; import { AppModule } from './app.module'; import { AppComponent } from './app.component'; import { RouterModule } from '@angular/router';
@NgModule({ imports: [ BrowserModule.withServerTransition({ appId: 'serverApp' }), ServerModule, AppModule, RouterModule.forRoot([]) ], bootstrap: [AppComponent], exports: [AppModule] }) export class AppServerModule {}
3.在app.component.ts中使用TransferState服务将子页面的HTML嵌入到主HTML中。例如:
import { Component, OnInit } from '@angular/core'; import { TransferState, makeStateKey } from '@angular/platform-browser'; import { HttpClient } from '@angular/common/http';
const CHILD_HTML_KEY = makeStateKey('child-html');
@Component({
selector: 'app-root',
template:
})
export class AppComponent implements OnInit {
childHtml: string;
constructor( private http: HttpClient, private state: TransferState ) {}
ngOnInit() { this.childHtml = this.state.get(CHILD_HTML_KEY, ''); if (!this.childHtml) { this.http.get('/child-page').subscribe(html => { this.childHtml = html; this.state.set(CHILD_HTML_KEY, html); }); } } }
以上代码将子页面的HTML存储在TransferState
上一篇:Angular服务端渲染(SSR)和mapbox-gl库不兼容?
下一篇:Angular服务端渲染(SSR)中,transferState.get(key,null)返回null,但是在浏览器中能够看到对象