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、用户打开应用后不用登录就可以直接使用...
针对!浙江游戏大厅修改数据&q... 针对!浙江游戏大厅修改数据"原来确实有辅助软件"(哔哩哔哩)所有人都在同一条线上,像星星一样排成一排...
反观!贪吃蛇辅助器怎么下载&q... 反观!贪吃蛇辅助器怎么下载"竟然真的是有辅助教程"(哔哩哔哩)贪吃蛇辅助器怎么下载能透视中分为三种模...
截至目前!潮汕激k辅助&quo... 截至目前!潮汕激k辅助"都是确实有辅助工具"(哔哩哔哩)1)潮汕激k辅助免费钻石:进一步探索潮汕激k...
今天上午!乐平包王攻略&quo... 今天上午!乐平包王攻略"果然存在有辅助工具"(哔哩哔哩)1、实时乐平包王攻略透视辅助更新:用户可以随...
更值得关注的是!决战卡五星游戏... 更值得关注的是!决战卡五星游戏辅助器"切实存在有辅助工具"(哔哩哔哩)决战卡五星游戏辅助器是不是有人...
教学辅助挂!科米台州麻将辅助&... 教学辅助挂!科米台州麻将辅助"竟然是有辅助器"(哔哩哔哩)1、上手简单,内置详细流程视频教学,新手小...
相较于以往!来几局是正规平台吗... 相较于以往!来几局是正规平台吗"其实确实有辅助工具"(哔哩哔哩)来几局是正规平台吗脚本下载中分为三种...
最终!朱雀开心罗松怎么开挂&q... 最终!朱雀开心罗松怎么开挂"总是是有辅助挂"(哔哩哔哩)一、朱雀开心罗松怎么开挂游戏安装教程牌型概率...
2026版规律!新西楚辅助器&... 2026版规律!新西楚辅助器"竟然确实有辅助器"(哔哩哔哩)1、每一步都需要思考,不同水平的挑战新西...