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

在这个示

相关内容

热门资讯

透视必备!hhpoker免费辅... 透视必备!hhpoker免费辅助器,hhpoker真的有透视吗-一直有辅助app(哔哩哔哩)小薇(辅...
透视了解!wpk官网下载链接,... 透视了解!wpk官网下载链接,wpk辅助-真是一直总是有辅助技巧(哔哩哔哩)1、任何透视是真的假的的...
透视必备!wepoker有没有... 透视必备!wepoker有没有辅助,wepoker怎么获得好牌-一贯是有辅助技巧(哔哩哔哩)1)免费...
透视揭幕!we-poker是什... 透视揭幕!we-poker是什么软件,wejoker辅助机器人-都是一直总是有辅助工具(哔哩哔哩)透...
透视总结!wepoker辅助脚... 透视总结!wepoker辅助脚本,wepoker怎么设置盖牌-确实是真的有辅助攻略(哔哩哔哩)1、该...
透视必备!wpk俱乐部辅助器,... 透视必备!wpk俱乐部辅助器,wpk俱乐部怎么作弊-都是一直总是有辅助app(哔哩哔哩);1、完成辅...
透视解谜!wpk德州局怎么透视... 透视解谜!wpk德州局怎么透视,wpk透视辅助靠谱吗-切实有辅助方法(哔哩哔哩)德州局怎么透视破解侠...
透视揭露!wepoker模拟器... 透视揭露!wepoker模拟器哪个,we-poker靠谱吗-竟然存在有辅助神器(哔哩哔哩)在进入软件...
透视辅助!hhpoker有没有... 透视辅助!hhpoker有没有作弊辅助,hhpoker是内部控制吗-总是是有辅助软件(哔哩哔哩)1、...
透视普及!aapoker透视插... 透视普及!aapoker透视插件,aapoker万能辅助器-好像一直总是有辅助神器(哔哩哔哩)一、可...