AngularUniversal是否可以在响应客户端之前从服务器执行HTTP请求以构建页面?
创始人
2024-10-29 21:01:07
0次

可以使用Angular Universal的TransferState模块和HttpClient模块将HTTP请求从服务器转移到客户端。

以下是示例代码:

//app.module.ts

import { BrowserModule, BrowserTransferStateModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { HttpClientModule, HttpClient } from '@angular/common/http'; import { TransferHttpCacheModule } from '@nguniversal/common'; import { AppComponent } from './app.component';

@NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule.withServerTransition({appId: 'my-app'}), HttpClientModule, BrowserTransferStateModule, TransferHttpCacheModule, ], providers: [ HttpClient, ], bootstrap: [AppComponent] }) export class AppModule { }

//app.component.ts

import { Component, OnInit, Inject, PLATFORM_ID } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { isPlatformServer } from '@angular/common'; import { TransferState, makeStateKey } from '@angular/platform-browser';

const SERVER_INIT_KEY = makeStateKey('server-init');

@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { title = 'my-app'; dataFromServer: any;

constructor( private http: HttpClient, private transferState: TransferState, @Inject(PLATFORM_ID) private platformId: Object ) { }

ngOnInit() { if (isPlatformServer(this.platformId)) { // Server side rendering this.dataFromServer = 'This data came from the server'; this.transferState.set(SERVER_INIT_KEY, true); } else { // Browser rendering const serverInit = this.transferState.get(SERVER_INIT_KEY, false); if (!serverInit) { // This data didn't come from the server, so fetch it this.http.get('/api/data').subscribe(data => { this.dataFromServer = data; }); } else { // This data came from the server this.dataFromServer = this.transferState.get('dataFromServer', null); } } } }

在这个示

相关内容

热门资讯

WPK作弊窍要!德扑之星透视辅... WPK作弊窍要!德扑之星透视辅助插件,菠萝智星德州ai多功能透视脚本1、德扑之星透视辅助插件辅助软件...
WPK模拟器方式!拱趴大菠萝万... WPK模拟器方式!拱趴大菠萝万能挂,智星菠萝德州ai多功能透视挂技巧1、拱趴大菠萝万能挂辅助器安装包...
WPK德州局秘籍!拱趴大菠萝辅... WPK德州局秘籍!拱趴大菠萝辅助神器,微扑克ai多功能辅助器脚本1、金币登录送、破产送、升级送、活动...
WPK安装手筋!德扑之星有辅助... WPK安装手筋!德扑之星有辅助软件吗,微扑克ai多功能透视脚本德扑之星有辅助软件吗能透视中分为三种模...
WPK方法秘籍!werplan... WPK方法秘籍!werplan外挂,德扑之星ai多功能开挂神器1、这是跨平台的werplan外挂轻量...
WPK私人局总结!德州局透视,... WPK私人局总结!德州局透视,wpkai多功能开挂教程1)德州局透视辅助插件:进一步探索德州局透视辅...
WPK安卓操作!aapoker... WPK安卓操作!aapoker辅助工具安全吗,微扑克ai多功能辅助软件1、金币登录送、破产送、升级送...
WPK透视窍门!AApoker... WPK透视窍门!AApoker软件,aapokerai多功能辅助神器1、实时AApoker软件透视辅...
WPK脚本烘培!aapoker... WPK脚本烘培!aapoker辅助怎么用,WePoKerai多功能透视挂技巧1、全新机制【aapok...
WPK软件法子!aapoker... WPK软件法子!aapoker公共底牌,红龙扑克ai多功能开挂工具1、aapoker公共底牌公共底牌...