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

在这个示

相关内容

热门资讯

第1分钟了解!jj斗地主有透视... 第1分钟了解!jj斗地主有透视吗!切实真的是有辅助攻略(新版有挂)-哔哩哔哩1、在jj斗地主有透视吗...
第3分钟了解!楚天游卡五星辅助... 第3分钟了解!楚天游卡五星辅助器!总是一直总是有辅助技巧(有挂教学)-哔哩哔哩1、第3分钟了解!楚天...
8分钟了解!hhpoker辅助... 8分钟了解!hhpoker辅助是真的吗!都是是有辅助神器(有挂方针)-哔哩哔哩1、完成hhpoker...
九分钟了解!透视辅助器免费欢聚... 九分钟了解!透视辅助器免费欢聚水鱼!本来一直都是有辅助软件(真是有挂)-哔哩哔哩1、透视辅助器免费欢...
九分钟了解!晋中胡乐辅助工具!... 九分钟了解!晋中胡乐辅助工具!本来真的有辅助app(有挂工具)-哔哩哔哩暗藏猫腻,小编详细说明晋中胡...
第二分钟了解!四川熊猫辅助器!... 第二分钟了解!四川熊猫辅助器!原来一直总是有辅助脚本(有挂攻略)-哔哩哔哩四川熊猫辅助器辅助器是一种...
第八分钟了解!打哈儿辅助软件!... 第八分钟了解!打哈儿辅助软件!本来是有辅助app(有挂助手)-哔哩哔哩一、打哈儿辅助软件可以开透视的...
第5分钟了解!欢游互动辅助!本... 第5分钟了解!欢游互动辅助!本来一直总是有辅助软件(竟然有挂)-哔哩哔哩1、许多玩家不知道欢游互动辅...
7分钟了解!欢聚水鱼智能辅助教... 7分钟了解!欢聚水鱼智能辅助教程!果然是真的有辅助技巧(有挂详情)-哔哩哔哩1、用户打开应用后不用登...
1分钟了解!微乐斗地主有挂吗!... 1分钟了解!微乐斗地主有挂吗!本来是有辅助技巧(有挂解惑)-哔哩哔哩1、微乐斗地主有挂吗辅助器安装包...