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分钟了解!仙桃晃晃诀窍!一贯... 1分钟了解!仙桃晃晃诀窍!一贯存在有辅助脚本(有挂助手)-哔哩哔哩;1、点击下载安装,仙桃晃晃诀窍脚...
6分钟了解!掌乐宝修改器!竟然... 6分钟了解!掌乐宝修改器!竟然是真的有辅助软件(有挂教程)-哔哩哔哩暗藏猫腻,小编详细说明掌乐宝修改...
第8分钟了解!广西八一字牌外g... 第8分钟了解!广西八一字牌外g挂安装!其实存在有辅助工具(有挂透视)-哔哩哔哩1、在广西八一字牌外g...
4分钟了解!凑一桌关春天怎么才... 4分钟了解!凑一桌关春天怎么才能开挂!本来一直总是有辅助攻略(证实有挂)-哔哩哔哩凑一桌关春天怎么才...
第一分钟了解!老友广东麻将有挂... 第一分钟了解!老友广东麻将有挂吗!真是真的是有辅助插件(有挂详情)-哔哩哔哩一、老友广东麻将有挂吗游...
第七分钟了解!威信茶馆有挂的吗... 第七分钟了解!威信茶馆有挂的吗!一贯是有辅助技巧(今日头条)-哔哩哔哩一、威信茶馆有挂的吗游戏安装教...
4分钟了解!九天大厅挂价格!总... 4分钟了解!九天大厅挂价格!总是一直都是有辅助方法(有挂技巧)-哔哩哔哩九天大厅挂价格脚本下载中分为...
一分钟了解!人海大厅挂件怎么买... 一分钟了解!人海大厅挂件怎么买!一直一直都是有辅助技巧(竟然有挂)-哔哩哔哩小薇(辅助器软件下载)致...
第六分钟了解!游戏黑科技夫追求... 第六分钟了解!游戏黑科技夫追求!切实一直总是有辅助工具(确实有挂)-哔哩哔哩1、完成游戏黑科技夫追求...