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

在这个示

相关内容

热门资讯

发现玩家!wejoker黑侠辅... 发现玩家!wejoker黑侠辅助器,wepoker破解游戏盒子,总结教程(有挂软件);亲真的是有正版...
推荐一款!wepoker透视最... 1、推荐一款!wepoker透视最简单三个步骤,wepoker辅助器下载,教你攻略(有挂辅助)。2、...
分享认知!hhpoker透视脚... 分享认知!hhpoker透视脚本下载,wepoker辅助器免费,透明挂教程(有挂透明)准备好在hhp...
重大通报!wpk刷入池率脚本,... 重大通报!wpk刷入池率脚本,大菠萝手游辅助,必胜教程(有挂辅助);建议优先通过大菠萝手游辅助透明挂...
玩家必看科普!哈糖大菠萝有挂吗... 玩家必看科普!哈糖大菠萝有挂吗,佛手在线是不是有挂,透明挂教程(有挂技巧);佛手在线是不是有挂软件透...
一分钟教会你!wejoker辅... 1、一分钟教会你!wejoker辅助软件,德州来玩辅助器,攻略教程(有挂攻略)2、进入游戏-大厅左侧...
玩家必看科普!wpk俱乐部辅助... 玩家必看科普!wpk俱乐部辅助器,拱趴大菠萝万能辅助器,插件教程(有挂神器)关于拱趴大菠萝万能辅助器...
教程辅助!wepokerplu... 此外,数据分析德州(wepokerplus到底是挂了吗)辅助神器app还具备辅助透视行为开挂功能,通...
玩家交流!wepoker辅助是... 玩家交流!wepoker辅助是真的假的,pokemmo手机版脚本,德州论坛(有挂透视);原来确实真的...
一分钟揭秘!德州局怎么透视,智... 一分钟揭秘!德州局怎么透视,智星菠萝可以辅助吗,第三方教程(有挂攻略);科技安装教程;1367043...