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

在这个示

相关内容

热门资讯

据相关数据显示!hhpoker... 据相关数据显示!hhpoker万能辅助器,xpoker辅助,总是存在有辅助技巧(哔哩哔哩)1)xpo...
备受关注的!德普之星app安卓... 备受关注的!德普之星app安卓版破解版,随意玩有没有辅助,竟然存在有辅助方法(哔哩哔哩)1、进入游戏...
迎来新发展!wepoker私局... 迎来新发展!wepoker私局代打,小程序广东雀神智能挂件,本来是真的有辅助脚本(哔哩哔哩)1、下载...
随着!pokemmo脚本辅助下... 随着!pokemmo脚本辅助下载,微信小程序透视挂,一贯存在有辅助工具(哔哩哔哩)pokemmo脚本...
推出新举措!约局吧辅助器,潮友... 推出新举措!约局吧辅助器,潮友会鱼虾蟹破解,都是真的是有辅助技巧(哔哩哔哩)进入游戏-大厅左侧-新手...
受玩家影响!拱趴大菠萝有挂吗,... 您好,拱趴大菠萝有挂吗这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩...
近期!约局吧德州真的有透视挂吗... 近期!约局吧德州真的有透视挂吗,微信微乐小程序修改器,其实真的有辅助教程(哔哩哔哩)1、全新机制【约...
目前!wepoker私人定制透... 目前!wepoker私人定制透视,pokeplus脚本,竟然是真的有辅助工具(哔哩哔哩)1、poke...
长期以来!we poker免费... 长期以来!we poker免费辅助器,新玉海楼茶苑脚本,切实真的有辅助教程(哔哩哔哩)1、起透看视 ...
今天下午!hhpoker有没有... 今天下午!hhpoker有没有辅助,随意玩5元流量包,好像存在有辅助工具(哔哩哔哩)1、不需要AI权...