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); } } } }

在这个示

相关内容

热门资讯

第九分钟透视!微乐小程序免费黑... 第九分钟透视!微乐小程序免费黑科技,微乐自建房安装挂(开挂)真是有挂(2026)1、进入到微乐小程序...
透视了解!微乐小程序黑科技,微... 透视了解!微乐小程序黑科技,微乐小程序辅助脚本靠谱的(透视)竟然真的有挂(哔哩哔哩)1、许多玩家不知...
第3分钟脚本!微乐小程序黑科技... 第3分钟脚本!微乐小程序黑科技,微信小程序微乐辅助器破解版(开挂)果然有挂(2026)1、微乐小程序...
方法辅助挂!微乐小程序黑科技,... 方法辅助挂!微乐小程序黑科技,微乐小程序黑科技免费知乎(透视)原来是真的挂(哔哩哔哩)运微乐小程序黑...
不少玩家反映!微乐小程序黑科技... 不少玩家反映!微乐小程序黑科技,微信小程序微乐辅助器免费下载(透视)好像有挂(哔哩哔哩)1、很好的工...
九分钟透视!微乐小程序免费黑科... 九分钟透视!微乐小程序免费黑科技,微乐智能辅助软件是真的吗(开挂)切实是真的挂(2026)在进入微乐...
9分钟教程!微乐小程序免费黑科... 9分钟教程!微乐小程序免费黑科技,微信小程序微乐为什么老输(开挂)确实真的是有挂(2026)1、该软...
黑科技辅助挂!微乐小程序免费黑... 黑科技辅助挂!微乐小程序免费黑科技,微乐广西小程序开挂(透视)竟然有挂(哔哩哔哩)1、操作简单,无需...
第三分钟安装!微乐小程序黑科技... 第三分钟安装!微乐小程序黑科技,如何下载微乐自建房黑科技入口(开挂)竟然真的有挂(2026)1、下载...
黑科技辅助挂!微乐小程序黑科技... 黑科技辅助挂!微乐小程序黑科技,微信小程序游戏破解微乐辅助(透视)果然是真的挂(哔哩哔哩)1、打开软...