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

在这个示

相关内容

热门资讯

详情透视!wepoker软件辅... 详情透视!wepoker软件辅助程序,微信小程序微乐辅助器苹果,绝活教程(有挂规律)-哔哩哔哩wep...
专业透视!wepoker破解工... 专业透视!wepoker破解工具,微乐江苏小程序游戏破解下载,窍门教程(有挂详情)-哔哩哔哩1、金币...
教你透视!wepoker养号规... 教你透视!wepoker养号规律,微乐小程序有脚本,秘籍教程(有挂攻略)-哔哩哔哩1、下载好wepo...
普及透视!wepoker手机版... 普及透视!wepoker手机版透视脚本,微乐小程序卡五星脚本,绝活儿教程(有挂工具)-哔哩哔哩1、w...
有挂透视!约局吧是否有挂,微乐... 有挂透视!约局吧是否有挂,微乐小程序修复系统有用吗,练习教程(有挂神器)-哔哩哔哩1、让任何用户在无...
普及透视!wepoker私局代... 普及透视!wepoker私局代打,微乐小程序辅助脚本,绝活教程(有挂头条)-哔哩哔哩普及透视!wep...
分享透视!hhpoker辅助靠... 分享透视!hhpoker辅助靠谱吗,小程序微乐陕西挖坑辅助器,手段教程(有挂总结)-哔哩哔哩hhpo...
解密透视!hhpoker辅助器... 解密透视!hhpoker辅助器,微乐自建房辅助多少钱一个月,经验教程(果真有挂)-哔哩哔哩1、完成h...
解密透视!佛手大菠萝辅助,微乐... 解密透视!佛手大菠萝辅助,微乐自建房脚本如何下载,步骤教程(真是有挂)-哔哩哔哩佛手大菠萝辅助辅助器...
开挂透视!wepoker透视脚... 开挂透视!wepoker透视脚本视频,微乐小程序辅助,演示教程(有挂秘诀)-哔哩哔哩一、wepoke...