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

在这个示

相关内容

热门资讯

透视教你"wepok... 透视教你"wepoker有辅助工具吗"一贯存在有辅助工具(哔哩哔哩)1、打开软件启动之后找到中间准星...
透视推荐"poker... 透视推荐"pokerworld修改器"原来真的是有辅助器(哔哩哔哩)1、下载好pokerworld修...
透视解迷"pokem... 透视解迷"pokemmo辅助官网"本来有辅助攻略(哔哩哔哩)1、每一步都需要思考,不同水平的挑战会更...
透视揭露"wepok... 透视揭露"wepoker可以开透视吗"一直存在有辅助神器(哔哩哔哩)1、该软件可以轻松地帮助玩家将w...
透视曝光"wepok... 透视曝光"wepoker游戏的安装教程"切实是真的辅助教程(哔哩哔哩)亲,关键说明,wepoker游...
透视科普"wepok... 透视科普"wepoker作必弊辅助"其实是有辅助教程(哔哩哔哩)1、任何wepoker作必弊辅助透视...
透视有挂"wejok... 透视有挂"wejoker黑侠辅助器"果然真的是有辅助攻略(哔哩哔哩)1、让任何用户在无需wejoke...
透视必备"pokem... 您好,pokemmo修改器手机版这款游戏可以开挂的,确实是有挂的,需要了解加去威信【48527505...
透视专业"wepok... 透视专业"wepoker正确养号方法"果然真的有辅助神器(哔哩哔哩)亲,关键说明,wepoker正确...
透视辅助"wpk软件... 透视辅助"wpk软件是正规的吗"一贯是真的辅助软件(哔哩哔哩)1、wpk软件是正规的吗透视辅助软件激...