gpt4 book ai didi

c# - 在基于 Angular Cli 的应用程序中将数据从 ASP.NET Core 传递到 Typescript

转载 作者:太空狗 更新时间:2023-10-29 17:58:38 25 4
gpt4 key购买 nike

我正在尝试设置一个 SPA,我可以在其中将数据从我的 appsettings.json 传递到服务器渲染上的客户端。我按照步骤使用新的 SpaServices 模板配置 SSR

https://learn.microsoft.com/en-us/aspnet/core/spa/angular

但是我不明白如何完成这里标记的任务

You can pass this to other parts of your app in any way supported by Angular

我看到使用的示例是 base_url,但似乎 base 作为 DOM 元素注入(inject)到页面中

 <base href='/'>

但不清楚如何以这种方式阅读其他项目。我正在测试通过该应用程序是否为 Https,我的 Startup.cs 中有此部分

options.SupplyData = (context, data) =>
{
data["isHttpsRequest"] = context.Request.IsHttps;
};

在 main.server.ts 中

 { provide: 'isHttps', useValue: params.data.isHttpsRequest }

但是在 main.ts 中我迷路了,我有这样的东西

export function getBaseUrl() {
return document.getElementsByTagName('base')[0].href;
}

export function getIsHttps() {
// NO idea what needs to go here
return "";
}

const providers = [
{ provide: 'BASE_URL', useFactory: getBaseUrl, deps: [] },
{ provide: 'isHttps', useFactory: getIsHttps, deps: [] }
];

我不确定 SpaServices 如何将 Prerender 上的值注入(inject)到应用程序中(我查看了代码,但我不清楚)。值是否放在窗口上?如何读取该值以便注入(inject)到组件的构造函数中?

最佳答案

找到答案。你可以使用 Angular 的官方 TransferState .您需要修改以下文件

app.server.module.ts (添加 ServerTransferStateModule)

import { NgModule } from '@angular/core';
import { ServerModule, ServerTransferStateModule } from '@angular/platform-server';

import { AppModule } from './app.module';
import { AppComponent } from './app.component';

@NgModule({
imports: [
AppModule,
ServerModule,
ServerTransferStateModule
],
bootstrap: [AppComponent],
})
export class AppServerModule { }

app.module.ts (添加 BrowserTransferStateModule)

import { BrowserModule, BrowserTransferStateModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';

@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule.withServerTransition({ appId: 'universal-demo-v5' }),
HttpClientModule,
BrowserTransferStateModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

这添加了使用 TransferState 所需的模块。

然后,您需要在 main.server.ts 上提供 dotnet 服务器发送的值,并在 main.ts 上添加一个虚拟提供程序,以免引发冲突。

ma​​in.server.ts

import "zone.js/dist/zone-node";
import "reflect-metadata";
import { renderModule, renderModuleFactory } from "@angular/platform-server";
import { APP_BASE_HREF } from "@angular/common";
import { enableProdMode } from "@angular/core";
import { provideModuleMap } from "@nguniversal/module-map-ngfactory-loader";
import { createServerRenderer } from "aspnet-prerendering";
export { AppServerModule } from "./app/app.server.module";

enableProdMode();

export default createServerRenderer(params => {
const { AppServerModule, AppServerModuleNgFactory, LAZY_MODULE_MAP } = (module as any).exports;

const options = {
document: params.data.originalHtml,
url: params.url,
extraProviders: [
provideModuleMap(LAZY_MODULE_MAP),
{ provide: APP_BASE_HREF, useValue: params.baseUrl },
{ provide: "BASE_URL", useValue: params.origin + params.baseUrl},

//Added provider, ServerParams is the data sent on Startup.cs
{ provide: "SERVER_PARAMS", useValue: params.data.ServerParams }
]
};

const renderPromise = AppServerModuleNgFactory
? /* AoT */ renderModuleFactory(AppServerModuleNgFactory, options)
: /* dev */ renderModule(AppServerModule, options);

return renderPromise.then(html => ({ html }));
});

ma​​in.ts (仅当 DOM 完成加载时添加虚拟提供程序和 Bootstrap 应用程序。这将使我们有时间在 TransferState 上完全保存对象)

import { enableProdMode } from "@angular/core";
import { platformBrowserDynamic } from "@angular/platform-browser-dynamic";

import { AppModule } from "./app/app.module";
import { environment } from "./environments/environment";

export function getBaseUrl() {
return document.getElementsByTagName("base")[0].href;
}

const providers = [
{ provide: "BASE_URL", useFactory: getBaseUrl, deps: [] },
{ provide: "SERVER_PARAMS", useValue: "" }
];

if (environment.production) {
enableProdMode();
}

document.addEventListener("DOMContentLoaded", () => {
platformBrowserDynamic(providers)
.bootstrapModule(AppModule)
.catch(err => console.log(err));
});

最后,我们将服务器提供的对象保存在 app.component.ts 上的 TransferState

app.component.ts

import { Component, Inject } from "@angular/core";
import { TransferState, makeStateKey } from "@angular/platform-browser";

const SERVER_PARAMS = makeStateKey("serverParams");
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
serverParams: any;
// Provider set on main.ts and main.server.ts
constructor(@Inject("SERVER_PARAMS") private stateInj: string, private state: TransferState) {
this.serverParams = this.state.get(SERVER_PARAMS, null as any);

if (!this.serverParams) {
this.state.set(SERVER_PARAMS, stateInj as any);
}
}
}

就是这样

现在您可以在任何组件上使用 Transfer state 来获取数据

home.component.ts

import { Component, Inject } from "@angular/core";
import { TransferState, makeStateKey } from "@angular/platform-browser";

const SERVER_PARAMS = makeStateKey("serverParams");

@Component({
selector: "app-home",
templateUrl: "./home.component.html"
})
export class HomeComponent {
serverParameter = "PLACEHOLDER";
constructor(public state: TransferState) {}

ngOnInit() {
this.serverParameter = this.state.get(SERVER_PARAMS, "");
}
}

关于c# - 在基于 Angular Cli 的应用程序中将数据从 ASP.NET Core 传递到 Typescript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49329154/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com