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、下载好透视辅助下...
微乐小程序透视辅助!微信小程序... 微乐小程序透视辅助!微信小程序微乐辅助器下载(开挂)app-一贯科普存在有挂1、首先打开辅助器下载最...
微乐小程序黑科技免费!微信小程... 微乐小程序黑科技免费!微信小程序微乐为什么老输(开挂)神器-一贯普及真的是有挂是不是有人用挂微扑克w...
微乐小程序透视挂!微信微乐辅助... 微乐小程序透视挂!微信微乐辅助ios(开挂)神器-本来有挂是有挂1、让任何用户在无需安装教程第三方神...
微乐小程序透视辅助!微乐云南小... 微乐小程序透视辅助!微乐云南小程序辅助器(开挂)教程-确实解谜真的有挂是不是有人用挂微扑克wpk插件...
微乐小程序存在有挂!微乐自建房... 微乐小程序存在有挂!微乐自建房辅助软件下载(开挂)工具-都是曝光有挂1、玩家可以在透视最简单三个步骤...
微乐小程序黑科技!微乐房间辅助... 微乐小程序黑科技!微乐房间辅助工具在哪下载(开挂)教程-本来教你真的有挂1、打开软件启动之后找到中间...
微乐小程序存在有挂!小程序微乐... 微乐小程序存在有挂!小程序微乐游戏辅助器(开挂)技巧-其实推荐存在有挂是不是有人用挂微扑克wpk插件...